通过键路径PHP获取数组值 [英] Get array values by key path PHP

查看:131
本文介绍了通过键路径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. 我知道直到名称为"Mark"的数组的所有键,我需要一个递归函数来获取与此等效的数组:$ data ['properties'] [0] ['properties] [1] [properties] [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!!!

推荐答案

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

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天全站免登陆