通过关键路径的递归函数的PHP获得数组值 [英] get array values by key path recursive function php

查看:153
本文介绍了通过关键路径的递归函数的PHP获得数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

阵列路径是:0/1/0。
我知道,直到一个名为标记阵列中所有的钥匙,我需要一个递归函数来摆脱这种阵列相当于此:$数据[属性] [0] ['性质] [1] [属性] [0] 。请帮助我!

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!!!

推荐答案

我会用引用,而不是递归,但也许有人会用递归函数回答。如果您知道名称键,然后把它的路径。如果没有那么重置将得到第一个项目:

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

这篇关于通过关键路径的递归函数的PHP获得数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆