I am always trying to create the best and fastest code to keep improving my skills. Today I have to retrieve values from a multidimensional array dynamically. I have a piece of code, but I am not proud of it:
private function get_value_multidimensional_array($haystack, $route, $needle) {
switch (count($route)) {
case 1:
return $haystack[$route[0]][$needle];
break;
case 2:
return $haystack[$route[0]][$route[1]][$needle];
break;
case 3:
return $haystack[$route[0]][$route[1]][$route[2]][$needle];
break;
case 4:
return $haystack[$route[0]][$route[1]][$route[2]][$route[3]][$needle];
break;
}
}
INFORMATION
'$route' is an array that contains all the key steps. Because a key in the array is not necessarily unique, I have to use the route to get the correct position of the value.
An example of an array:
Array
(
[footer_columns] => Array
(
[empty_column_0] => false
[column_0] => Array
(
[news_widget_toggle] => false
[column_logo_toggle] => false
[column_0_image] => Array
(
[column_image] => http://placehold.it/150x100&text=afbeelding
)
)
[empty_column_1] => false
[column_1] => Array
(
[news_widget_toggle] => false
[column_logo_toggle] => false
[column_1_image] => Array
(
[column_image] => http://placehold.it/150x100&text=afbeelding
)
)
etc...
To get to the 'column_image' value, $route =
array('footer_columns','column_0','column_0_image')
The $needle value = 'column_image'.
QUESTION
Is there any way to optimize my function get_value_multidimensional_array() in that I can dynamically get the array value?
EDIT
This question might be a duplicate, but the answer in the 'original' has ZERO explanation. I am not asking this question to get a copy-paste section of code, I am asking this question to improve my coding skills!