There is a multilevel array of type

$arr = [ 'a' => 1, 'b' => 2, 'c' => [ 'a' => 1, 'b' => 2, 'c' => [ 'a' => 1, 'b' => 2, 'c' => [ 'd' => 3, 'e' => 4, 'f' => 5, ], ], ], ]; 

I need to get to the last C array and return it. I understand that some recursive function is needed, but I don’t understand how to write it. Since this is just an example, my array can contain both 10 levels and more ...

  • 2
  • do you have c in all the keys? or they may be different? among the elements on one level can there be only one array? and does it have a key с or does it have to find an array with maximum nesting? - teran
  • Yes, all keys are called the same. You need to get to the most nested and return its contents. At one level there can be two or more such arrays - Maxim

1 answer 1

Based on the author's comment: "I just need an array of с , that is, the last one that is called с "

  $arr = [ 'b' => 2, 'c' => [ 'b' => 2, 'c' => [ 'e' => 4, 'f' => 5, ], ], ]; function findLastArray($array) { if (array_key_exists('c', $array) && is_array($array['c'])) { return findLastArray($array['c']); } else { return $array; } } $lastArray = findLastArray($arr); 
  • The method above simply returns the most nested array, but I need an array of с , that is, the last one called с - Max
  • Then you need to consider the names of the keys and inside the loop in the condition add `&& $ key === 'c'`. Made a change in response - Grulex
  • Rewrote again. In your case it is even easier, you can use the function array_key_exists - Grulex
  • Rather, it means, you need to find the last nested array, and not specifically c array. And if in the array of arrays there is an array in which there are no more arrays, return. Otherwise, continue the search. - And
  • The author wrote "I just need an array of с , that is, the last one that is called с " - Grulex