PHP
10
Вклад в тег
/**
* @param array $array
* @param array $keyPath
* @param $value
*
* @return array
* @throws InvalidArgumentException
*/
function addValueToArrayByKeyPath ($array, $keyPath, $value) {
if (!is_array($array)) throw new \InvalidArgumentException;
$level =& $array;
foreach ($keyPath as $key) {
if (!array_key_exists($key, $level) or !is_array($level[$key])) {
$level[$key] = [];
}
$level =& $level[$key];
}
$level = $value;
return $array;
}
$array = [
1 => [
2 => [],
9 => [],
]
];
$keyPath = [1, 2 ,3];
$array = addValueToArrayByKeyPath($array, $keyPath, 42);
var_dump($array);
/* output:
array (size=1)
1 =>
array (size=2)
2 =>
array (size=1)
3 => int 42
9 =>
array (size=0)
empty
*/