简体   繁体   English

如何获取多维数组中某个键的子键?

[英]How can I get the child key of a key in a multidimensional array?

array(
   'World'=>array(
            'Asia'=>array(
               'Japan'=>array(
                    'City'=>'Tokyo'
               )
          )
     )
);

In my array I am searching for a key:在我的数组中,我正在寻找一个键:

foreach ($array as $key => $item) {
   if(is_array($item)){
      if (stripos($key, "Japan") !== false){
         echo $key;
      }
   }
}

The result is Japan .结果是Japan

For each key I want to check if the child key is "City".对于每个键,我想检查子键是否为“城市”。 So I did the following:所以我做了以下事情:

   foreach ($array as $key => $item) {
       if(is_array($item)){
          if (stripos($key, "Japan") !== false){
             echo $key;
             foreach ($key as $k => $i) {
                if (stripos($k, "City") !== false){
                   echo "true";
               } else {
                   echo "false";
              }
          }
       }
    }

I expect the result Japan true or at least the result Japan false but the result is still only Japan I do not understand.我希望结果Japan true或至少结果Japan false但结果仍然只是Japan我不明白。

In your second foreach your using a single element ( $key ) while you should use a set of elements ( $array[$key] , considering it's a multidimensional array).在您的第二个 foreach 中,您使用单个元素( $key ),而您应该使用一组元素( $array[$key] ,考虑到它是一个多维数组)。

foreach ($array as $key => $item) {
       if(is_array($item)){
          if (stripos($key, "Japan") !== false){
             echo $key;
             foreach ($array[$key] as $k => $i) {
                if (stripos($k, "City") !== false){
                   echo "true";
               } else {
                   echo "false";
              }
          }
       }
    }

I'd go with a recursion algorithm to solve the problem:我会用递归算法来解决这个问题:

function find_array_children_key($array, $children_key, $parent_key=''){
    $returning_value = false;
    if(is_array($array))
    {
        foreach($array as $key=>$value)
        {
            if($key===$children_key)
                $returning_value = $parent_key;
            else
                $returning_value = find_array_children_key($array,$children_key,$key);

            if($returning_value!==false)
                break;
        }
    }

    return $returning_value;
} 

Which you'd call, for instance in your case, find_array_children_key($array,'City')例如,在您的情况下,您会调用find_array_children_key($array,'City')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM