dqoys62082 2017-06-05 19:38
浏览 81
已采纳

如何获取php中第一次出现的array_walk_recursive的值

I have a deep multidimensional array that I am needing to extract the value of a specific key. I have found that the array_walk_recursive function will be my best option. I only need the first occurrence.

My array looks like this - (except much more complicated)

Array (
    [vehicle info] => Array (
        [one] => Array (
            [submodel] => LX
            [engine] => 2.3
        )
        [two] => Array (
            [color] => blue
            [year] => 2007
            [wheels] => 4
        )
        [three] => Array (
            [submodel] => LX
            [make] => Ford
            [model] => F-150
            [offroad] => No
        )
    )
)

The issue here is, submodel is in both one and three. Additionally, the array is not consistent, so I must use array_walk_recursive to search through it for the matching key, then return the value for that key.

Here is my current code -

array_walk_recursive ($array, (function ($item, $key) {
    $wanted = "submodel";
    if ($key === $wanted) {
        echo ("$key is $item");
    }
}));

The above returns submodel is LXsubmodel is LX.

Bonus Question!! How can I search for multiple keys and return the first corresponding value for each of those? I was thinking putting all wanted keys in an array, then do a foreach loop, but don't quite know how to structure this. I am new to php.

  • 写回答

4条回答 默认 最新

  • doubingjiu3199 2017-06-05 20:18
    关注

    Code:

    $array=['vehicle info'=>[
            'one'=>['submodel'=>'LX','engine'=>2.3],
            'two'=>['color'=>'blue','year'=>2007,'wheels'=>4],
            'three'=>['submodel'=>'LX','make'=>'Ford','model'=>'F-150','offroad'=>'No']
        ]
    ];
    
    $find=['submodel','offroad'];
    
    array_walk_recursive($array,function($v,$k)use($find,&$result){
        if(in_array($k,$find) && !isset($result[$k])){
            $result[$k]="$k is $v";
        }
    });
    var_export($result);
    

    Output:

    array (
      'submodel' => 'submodel is LX',
      'offroad' => 'offroad is No',
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题