【问题标题】:Get array values by key path PHP [duplicate]通过键路径PHP获取数组值[重复]
【发布时间】:2014-12-19 10:27:35
【问题描述】:

我有一个小问题。这是我的数组:

$data = array(
    'properties'=>array{
         [0]=>
             array {
                 ["name"]=>"prop1",
                 ["properties"]=>
                 array {
                     [0]=>
                         array(5) {
                             ["name"]=>"sub_prop1"
                         }
                     [1]=>
                         array(6) {
                             ["name"]=>"sub_prop2",
                             ["properties"]=>
                             array(2) {
                                  [0]=>
                                     array(6) {
                                          ["name"]=>"MARK"
                                     }
                             }
                       }
                }
        },
        [1]=>
            array {
                ["name"]=>"prop2"
           }
    }   
);

数组路径为:0/1/0。 我知道名称为“Mark”的数组之前的所有键,我需要一个递归函数来获取与此等效的数组:$data['properties'][0]['properties][1][properties][0] .请帮帮我!!!

【问题讨论】:

    标签: php arrays recursion path key


    【解决方案1】:

    我也找到了这个解决方案:

    function get_array_by_key_path($data, $key_path){
        if(count($key_path) == 0){
            return $data;        
        } 
        $key = array_shift($key_path);
        // and recursion now
        return get_array_by_key_path($data['properties'][$key], $key_path);
    }
    

    【讨论】:

      【解决方案2】:

      我会使用引用而不是递归,但也许有人会用递归函数来回答。如果您知道 name 键,请将其放在路径中。如果不是,那么reset 将获得第一项:

      $path = array('properties', 0, 'properties', 1, 'properties', 0);
      
      $result =& $data;
      
      foreach($path as $key) {
          $result =& $result[$key];
      }
      echo reset($result);
      
      // or if you want array('name' => 'MARK')
      print_r($result);
      

      【讨论】:

        猜你喜欢
        • 2016-09-20
        • 1970-01-01
        • 1970-01-01
        • 2013-09-23
        • 2018-03-29
        • 2011-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多