Jarla Jarla - 6 months ago 8
PHP Question

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
.

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.

Answer

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 ($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')

Comments