dongzhi1851 2014-07-20 15:46
浏览 61

如何用array_walk替换嵌套数组中的值?

How to replace values in a nested array with array_walk?

This is my array,

$item = array(
    "id" => "2",
    "title" => "parent 2",
    "children" => array (
           "id" => "4",
           "title" => "children 1"
        )
);

//replacement array:
$replace = [
  '2' => 'foo',
  '4' => 'bar',
  '7' => 'baz'
];

My working function,

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

result,

Array
(
    [id] => 2
    [title] => parent 2
    [children] => Array
        (
            [id] => 4
            [title] => children 1
        )

)

The result I'm after,

Array
(
    [id] => 2
    [title] => foo
    [children] => Array
        (
            [id] => 4
            [title] => bar
        )

)
  • 写回答

2条回答 默认 最新

  • doumao1519 2014-07-20 15:58
    关注

    This recursive function may help you

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

    it doesn't modify $item, it returns it modified, so you need to call it like this

    $item = replace($item,$replace);
    

    In order to make your function modify the argument $item, just pass it by reference like this :

    function replace(&$item,$replace)
    {
        foreach ($replace as $key => $value) 
        {
            if($item["id"]==$key)
                $item["title"] = $value;
            if(isset($item['children']))
                replace($item['children'],$replace);
        }
    }
    

    In this case you just need to call the function like this :

    replace($item,$replace);
    print_r($item);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。