Search for multidimensional array keys using another array

Is there an elegant way to get values ​​from a massive multidimensional array using another array to search for keys?

eg.

$cats[A][A1][A11][A111] = $val; $cats[A][A1][A11][A112] = $val; $cats[A][A1][A12] = $val; $cats[A][A1][A12][A121] = $val; $cats[A][A2] = $val; $cats[A][A2][A21] = $val; $cats[A][A2][A22] = $val; $cats[A][A2][A22][A221] = $val; $cats[A][A2][A22][A222] = $val; 

access values ​​from $cats using $keys = Array ('A', 'A2', 'A22', 'A221');

without checking the length of $keys and doing something like ...

 switch (count($keys)) { case 1: $val = $cats[$keys[0]]; break; case 2: $val = $cats[$key[0]][$key[1]]; break; case 3: $val = $cats[$key[0]][$key[1]][$key[2]]; break; ... } 

many thanks.

0
source share
3 answers

Why not use recursion? Something like that:

 function get_val($array, $keys) { if(empty($keys) || !is_array($keys) || !is_array($array)) return $array; else { $first_key = array_shift($keys); return get_val($array[$first_key], $keys); } } 

I originally wrote this in a loop, but for some reason I changed it to recursive. It is true, as Yeomen said, that a recursive function is more likely than a loop to cause a stack overflow, especially if your array is large enough (PHP supports trailing recursion), so here is a loop that should fulfill the same purpose:

 // given a multidimensional array $array and single-dimensional array of keys $keys $desired_value = $array; while(count($keys) > 0) { $first_key = array_shift($keys); $desired_value = $desired_value[$first_key]; } 
0
source

It is still. Otherwise, you will need to iterate over the array and check the depth. To make it dynamic, I'm sure that you add keys to the $ keys array when building $ cats. Using recursion, the solution will also require more steps, more memory.

0
source

jburbage suggesting using recursion is fine, but from what I know, PHP does not support finite recursion.

And the question was about a “massive” multidimensional array.

Since "massive" offers greater depth in addition to large size, stack overflow can be used with this solution, since it is usually possible to create data structures on the heap that reach deeper than the stack can handle with recursion.

This approach is also undesirable in terms of performance in this case.

Just a recursively recursive solution for working in a loop, and you're almost there :-)

Here is the jburbage original suggested code again:

 function get_val($array, $keys) { if(empty($keys) || !is_array($keys) || !is_array($array)) return $array; else { $first_key = array_shift($keys); return get_val($array[$first_key], $keys); } } 
0
source

Source: https://habr.com/ru/post/902336/


All Articles