基于Ugo Méda's response:
这个版本
- 允许您仅将其用作吸气剂(保持源数组不变)
- 修复了遇到非数组值时的致命错误问题 (
Cannot create references to/from string offsets nor overloaded objects)
没有致命错误示例
$a = ['foo'=>'not an array'];
arrayPath($a, ['foo','bar'], 'new value');
$a现在
array(
'foo' => array(
'bar' => 'new value',
),
)
用作吸气剂
$val = arrayPath($a, ['foo','bar']); // returns 'new value' / $a remains the same
将值设置为空
$v = null; // assign null to variable in order to pass by reference
$prevVal = arrayPath($a, ['foo','bar'], $v);
$prevVal 是“新值”
$a现在
array(
'foo' => array(
'bar' => null,
),
)
/**
* set/return a nested array value
*
* @param array $array the array to modify
* @param array $path the path to the value
* @param mixed $value (optional) value to set
*
* @return mixed previous value
*/
function arrayPath(&$array, $path = array(), &$value = null)
{
$args = func_get_args();
$ref = &$array;
foreach ($path as $key) {
if (!is_array($ref)) {
$ref = array();
}
$ref = &$ref[$key];
}
$prev = $ref;
if (array_key_exists(2, $args)) {
// value param was passed -> we're setting
$ref = $value; // set the value
}
return $prev;
}