Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Use array to get value in another, multidimensional array

This is a WordPress-specific context but my question is more PHP-related...

I'm finding myself in an odd situation where I need to get a value deep inside a multidimensional array, using another array that contains the sequence of keys in the correct order.

So essentially I have an array the looks something like

[0] => 'neighborhood' [1] => 'street' [2] => 'house'

And ultimately what I need is

get_option( $options_id )['neighborhood']['street']['house']

So basically I need to get the value of 'house' from the Options array by using another array to recurse down to it.

I can't do something like

foreach ( $array as $value ) {
    $sequence .= '[' $value ']';
}
get_option( $options_id ) . $sequence;

because that would fill $sequence with the values as a string. I've been trying things with explode() without any luck, but I'm not really a PHP wizard so I'm hoping there's some kind of obvious answer that I just haven't encountered before.

I know it's a weird situation but any help would be much appreciated!

like image 736
Shoelaced Avatar asked Apr 19 '26 03:04

Shoelaced


1 Answers

You might want to create some kind of helper function, where you iterate over parts of your path while keeping track of your temporary result:

function deep_array_get(array $path, array $subject) {

   $result = $subject;
   foreach ($path as $p) {
      $result = $result[$p];
   }

   return $result;

}

Example:

$p = ["a", "b", "c"];
$s = [1, 2, "a" => [3, 4, "b" => ["c" => 5]]];
var_dump(deep_array_get($p, $s));

// Result: int(5)

In your exact usecase it would be used something like this:

$path = ['neighborhood', 'street', 'house'];
$subject = get_option($options_id);

$result = deep_array_get($path, $subject);
like image 126
Smuuf Avatar answered Apr 21 '26 16:04

Smuuf