mirror of
https://github.com/yiisoft/yii2.git
synced 2026-03-23 15:37:24 +01:00
Fixes #6644: Added yii\helpers\ArrayHelper::setValue()
This commit is contained in:
@@ -214,6 +214,82 @@ class BaseArrayHelper
|
||||
return $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a value into an associative array at the key path specified.
|
||||
* If there is no such key path yet, it will be created recursively.
|
||||
* If the key exists, it will be overwritten.
|
||||
*
|
||||
* ```php
|
||||
* $array = [
|
||||
* 'key' => [
|
||||
* 'in' => [
|
||||
* 'val1',
|
||||
* 'key' => 'val'
|
||||
* ]
|
||||
* ]
|
||||
* ];
|
||||
* ```
|
||||
*
|
||||
* The result of `ArrayHelper::setValue($array, 'key.in.0', ['arr' => 'val']);` will be the following:
|
||||
*
|
||||
* ```php
|
||||
* [
|
||||
* 'key' => [
|
||||
* 'in' => [
|
||||
* ['arr' => 'val'],
|
||||
* 'key' => 'val'
|
||||
* ]
|
||||
* ]
|
||||
* ]
|
||||
*
|
||||
* ```
|
||||
*
|
||||
* The result of
|
||||
* `ArrayHelper::setValue($array, 'key.in', ['arr' => 'val']);` or
|
||||
* `ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);`
|
||||
* will be the following:
|
||||
*
|
||||
* ```php
|
||||
* [
|
||||
* 'key' => [
|
||||
* 'in' => [
|
||||
* 'arr' => 'val'
|
||||
* ]
|
||||
* ]
|
||||
* ]
|
||||
* ```
|
||||
*
|
||||
* @param array $array the array to write the value to
|
||||
* @param string|array|null $path the path of where do you want to write a value to `$array`
|
||||
* the path can be described by a string when each key should be separated by a dot
|
||||
* you can also describe the path as an array of keys
|
||||
* if the path is null then `$array` will be assigned the `$value`
|
||||
* @param mixed $value the value to be written
|
||||
* @since 2.0.13
|
||||
*/
|
||||
public static function setValue(&$array, $path, $value)
|
||||
{
|
||||
if ($path === null) {
|
||||
$array = $value;
|
||||
return;
|
||||
}
|
||||
|
||||
$keys = is_array($path) ? $path : explode('.', $path);
|
||||
|
||||
while (count($keys) > 1) {
|
||||
$key = array_shift($keys);
|
||||
if (!isset($array[$key])) {
|
||||
$array[$key] = [];
|
||||
}
|
||||
if (!is_array($array[$key])) {
|
||||
$array[$key] = [$array[$key]];
|
||||
}
|
||||
$array = &$array[$key];
|
||||
}
|
||||
|
||||
$array[array_shift($keys)] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes an item from an array and returns the value. If the key does not exist in the array, the default value
|
||||
* will be returned instead.
|
||||
|
||||
Reference in New Issue
Block a user