lau*_*kok 2 php multidimensional-array
如何使用array_walk 更改元素的值?
例如,这是我的阵列,
$items = array(
0 => array(
"id" => "1",
"title" => "parent 1",
"children" => array()
),
1 => array(
"id" => "2",
"title" => "parent 2",
"children" => array (
0 => array(
"id" => "4",
"title" => "children 1"
),
1 => array(
"id" => "5",
"title" => "children 2"
)
),
)
);
Run Code Online (Sandbox Code Playgroud)
我可以用下面这个改变它,
function myfunction(&$item,$key)
{
if($item['id'] === '1')
{
$item['title'] = 'hello world en';
}
}
array_walk($items,"myfunction");
print_r($items);
Run Code Online (Sandbox Code Playgroud)
但我有一个嵌套的孩子,我也想改变它的价值,如果我这样做,我会得到错误,
function myfunction(&$item,$key)
{
if($item['id'] === '1')
{
$item['title'] = 'hello world en';
}
if($item['id'] === '4')
{
$item['title'] = 'hello world en';
}
foreach($item as $key => $value)
{
if(is_array($value))
{
myfunction($value,$key);
}
}
}
Run Code Online (Sandbox Code Playgroud)
错误,
注意:未定义的索引:在xx行的... index.php中的id
如果数组中有嵌套子项,我该怎么办?
你可以通过递归调用你的回调函数来实现这一点.我已经实现了带闭包的样本,例如:
//replacement array:
$replace = [
'1' => 'foo',
'2' => 'bar',
'5' => 'baz'
];
array_walk($items, $f=function(&$value, $key) use (&$f, $replace)
{
if(isset($replace[$value['id']]))
{
$value['title'] = $replace[$value['id']];
}
if(isset($value['children']))
{
//the loop which is failing in question:
foreach($value['children'] as $k=>&$child)
{
$f($child, $k);
}
//Proper usage would be - to take advantage of $f
//array_walk($value['children'], $f);
}
});
Run Code Online (Sandbox Code Playgroud)
正如您所看到的 - 您需要的只是通过引用传递值并在回调内迭代它作为参考foreach.