dow58115 2016-04-05 15:09
浏览 32
已采纳

如何打印通过URL参数检测到的特定阵列的所有子项?

This is my array:

array(1) {
  ["farm"]=>
  array(1) {
    ["animals"]=>
    array(1) {
      [horses]=>
      array(4) {
        ["fred"]=>
        string(4) "fred"
        ["sam"]=>
        string(4) "sam"
        ["alan"]=>
        string(4) "alan"
        ["john"]=>
        string(4) "john"
      }
    }
  }
}

And this is my URL

mypage.php?id=2&dir=animals

I would like to print the children of my URL parameter dir(In this case:animals)

This is the way I try to do it:

 foreach($array as $sub) {
        if ($_GET['dir'] == $sub){
        $result = array_merge($result, $sub);
        echo $result;
        }
}

My result: An empty page.

The result I wish: horses

  • 写回答

2条回答 默认 最新

  • dongzi4030 2016-04-05 16:02
    关注

    Your array:

    $arr = array("farm" => 
                 array("animals"=>
                       array("horses" => 
                             array("fred" => "fred",
                                   "sam" => "sam",
                                   "alan" => "alan",
                                   "john" => "john")
                            )
                      )
                );
    

    Here we go, i make a recursive function for searching the value.

    This function not work if you search for fred and their siblings.

    $search = 'horses';
    get_values($arr);
    
    function get_values($arr){  
        global $search;
        foreach($arr as $key => $value){
            if($key == $search){
                if(is_array($value)){
                    echo join(", ", array_keys($value));
                }           
                else{
                    echo $value;
                }
            }else{
                get_values($value);
            }       
        }   
    }
    

    Output:

    fred, sam, alan, john

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 反激PWM控制芯片调研
  • ¥15 Python for loop减少运行时间
  • ¥15 fluent模拟物质浓度udf
  • ¥15 Collection contains no element matching the predicate
  • ¥20 冻品电商平台的搜索是怎么实现的
  • ¥15 如何搞一个可以控制、显示马达频率
  • ¥15 WPF动态创建页面内容
  • ¥15 如何对TBSS的结果进行统计学的分析已完成置换检验,如何在最终的TBSS输出结果提取除具体值及如何做进一步相关性分析
  • ¥15 SQL数据库操作问题
  • ¥100 关于lm339比较电路出现的问题