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

报告相同问题?

悬赏问题

  • ¥20 求计算赫斯特(Hurst)指数
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大