如何使用array_walk替换嵌套数组中的值?
这是我的数组,
$item = array(
"id" => "2",
"title" => "parent 2",
"children" => array (
"id" => "4",
"title" => "children 1"
)
);
//replacement array:
$replace = [
'2' => 'foo',
'4' => 'bar',
'7' => 'baz'
];
我的工作职能,
function myfunction(&$value,$key,$replace)
{
if(isset($replace[$key]))
{
$value = $replace[$key];
}
if(is_array($key))
{
array_walk($value,"myfunction",$replace);
}
}
array_walk($item,"myfunction",$replace);
print_r($item);
结果,
Array
(
[id] => 2
[title] => parent 2
[children] => Array
(
[id] => 4
[title] => children 1
)
)
我之后的结果,
Array
(
[id] => 2
[title] => foo
[children] => Array
(
[id] => 4
[title] => bar
)
)
答案 0 :(得分:2)
这个递归函数可以帮助你
function replace($item,$replace)
{
foreach ($replace as $key => $value)
{
if($item["id"]==$key)
$item["title"] = $value;
if(isset($item['children']))
$item['children'] = replace($item['children'],$replace);
}
return $item;
}
它不修改$ item,它返回修改后的内容,所以你需要像这样调用它
$item = replace($item,$replace);
为了让你的函数修改参数$ item,只需通过引用传递它:
function replace(&$item,$replace)
{
foreach ($replace as $key => $value)
{
if($item["id"]==$key)
$item["title"] = $value;
if(isset($item['children']))
replace($item['children'],$replace);
}
}
在这种情况下,你只需要调用这样的函数:
replace($item,$replace);
print_r($item);
答案 1 :(得分:0)
试试这个功能:
function replaceKey($subject, $newKey, $oldKey) {
if (!is_array($subject)) return $subject;
$newArray = array(); // empty array to hold copy of subject
foreach ($subject as $key => $value) {
// replace the key with the new key only if it is the old key
$key = ($key === $oldKey) ? $newKey : $key;
// add the value with the recursive call
$newArray[$key] = $this->replaceKey($value, $newKey, $oldKey);
}
return $newArray;
}