Shoelaced
Shoelaced

Reputation: 881

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!

Upvotes: 3

Views: 676

Answers (2)

Joseph_J
Joseph_J

Reputation: 3669

So if array always has the same format then I think the best thing to do would be like kry suggested.

//Example
$array = [0 => 'neighborhood', 1 => 'street', 2 => 'house'];

$options_id = [1,2,'neighborhood'=>[1,2,3,'street'=>[1,2,3,'house'=>[1,2,3,'myhouse']]]];

$result = $options_id[$array[0]][$array[1]][$array[2]];

print_r($result);

This will output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => myhouse
)

Your code.

$array = [0 => 'neighborhood', 1 => 'street', 2 => 'house'];

//I don't know Wordpress. You can try:
$result = get_option($options_id)[$array[0]][$array[1]][$array[2]]; 

//If that does not work.. Use this.
//$data = get_option($options_id);
//$result = $data[$array[0]][$array[1]][$array[2]];

print_r($result);

Upvotes: 0

Smuuf
Smuuf

Reputation: 6524

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);

Upvotes: 5

Related Questions