doulin4844 2017-09-14 07:43
浏览 44

使用一些外部键从PHP关联数组中提取内部数组

I have a array $a and some key arrays e.g. $keys1, $keys2,....

$a = array('a'=>array('b'=>array('c'=>array('d'=>123,'s'=>4),'r'=>3),'q'=>2),'p'=>1);

$keys1 = array('a','b','c');

$keys2 = array('a','b');

$a =  Array
    (
        [a] => Array
            (
                [b] => Array
                    (
                        [c] => Array
                            (
                                [d] => 123
                                [s] => 4
                            )

                        [r] => 3
                    )

                [q] => 2
            )

        [p] => 1
    )

whenever $keys1 is used, output should be

Array
(
    [d] => 123
    [s] => 4
)

or whenever $keys2 is used, output should be

Array
(
  [c] => Array
    (
        [d] => 123
        [s] => 4
    )
)

this is very simple I can achieve result by using $a[a][b][c] in first case and by using $a[a][b] in second case

Problem: these $keys are provided in form of array at run time, Is there any function in php to get the result?

  • 写回答

1条回答 默认 最新

  • douying1119 2017-09-14 07:58
    关注

    Try this.
    Comments are in code.

    It will loop through the keys and return the searched value.

    $a = array('a'=>array('b'=>array('c'=>array('d'=>123,'s'=>4),'r'=>3),'q'=>2),'p'=>1);
    
    $keys1 = array('a','b','c');
    
    $keys2 = array('a','b');
    $keys = $keys1; // set this as "search value"
    
    $value = $a; // create a copy of original array. Maybe not needed?
    Foreach($keys as $key){ // loop keys in search value
        $value = $value[$key]; // overwrite $value with subarray of $value[$key]
    }
    
    Var_dump($value); // dump the search return.
    

    https://3v4l.org/ZHBMa

    评论

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本