如何使用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"
)
),
)
);
我可以在下面对此进行更改,
function myfunction(&$item,$key)
{
if($item['id'] === '1')
{
$item['title'] = 'hello world en';
}
}
array_walk($items,"myfunction");
print_r($items);
但是我有一个嵌套的孩子,我也想更改其中的值,如果这样做,我会得到错误信息,
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);
}
}
}
错误,
注意:未定义的索引:第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);
}
});
如您所见-您所需要做的就是通过引用传递值,并将其在回调中进行迭代作为引用foreach
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句