"1", "tit-6ren">
gpt4 book ai didi

php - 如何使用 array_walk 更改元素的值?

转载 作者:行者123 更新时间:2023-12-02 06:33:51 24 4
gpt4 key购买 nike

如何使用 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);

但是我有一个嵌套的 child ,我也想更改其中的值,如果我这样做会出错,

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);
}
}

}

错误,

Notice: Undefined index: id in ...index.php on line xx

知道如果数组中有嵌套子项我该怎么办吗?

最佳答案

您可以通过递归调用回调函数来实现。我已经实现了带有闭包的示例,例如:

//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 的引用。

关于php - 如何使用 array_walk 更改元素的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24759065/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com