Get array values by key path PHP [duplicate]

2020-04-01 06:38发布

问题:

I have a little problem. Here is my array:

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

Array path is: 0/1/0. I know all the keys until array with name "Mark", I need a recursive function to get out this array equivalent with this: $data['properties'][0]['properties][1][properties][0]. Please help me!!!

回答1:

I would use references instead of recursion, but maybe someone will answer with a recursive function. If you know the name key then put it in the path. If not then the reset will get the first item:

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


回答2:

I found also this solution:

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