Fixes #6644: Added yii\helpers\ArrayHelper::setValue()

This commit is contained in:
Alex
2017-07-16 00:25:44 +03:00
committed by Alexander Makarov
parent 2f9f15bf92
commit 59002a9e1e
5 changed files with 421 additions and 2 deletions

View File

@@ -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.