Ben
Ben

Reputation: 11188

array values to nested array with PHP

I'm trying to figure out how I can use the values an indexed array as path for another array. I'm exploding a string to an array, and based on all values in that array I'm looking for a value in another array.

Example:

$haystack['my']['string']['is']['nested'] = 'Hello';
$var = 'my@string@is@nested';
$items = explode('@', $var);

// .. echo $haystack[... items..?]

The number of values may differ, so it's not an option to do just $haystack[$items[0][$items[1][$items[2][$items[3]].

Any suggestions?

Upvotes: 3

Views: 215

Answers (3)

user5192753
user5192753

Reputation:

Or you can use a recursive function:

function extractValue($array, $keys)
{
    return empty($keys) ? $array : extractValue($array[array_shift($keys)], $keys) ; 
}

$haystack = array('my' => array('string' => array('is' => array('nested' => 'hello'))));
echo extractValue($haystack, explode('@', 'my@string@is@nested'));

Upvotes: 2

Sougata Bose
Sougata Bose

Reputation: 31749

You can use a loop -

$haystack['my']['string']['is']['nested'] = 'Hello';
$var = 'my@string@is@nested';
$items = explode('@', $var);

$temp = $haystack;
foreach($items as $v) {
    $temp = $temp[$v]; // Store the current array value
}
echo $temp;

DEMO

Upvotes: 2

Jim
Jim

Reputation: 22656

You can use a loop to grab each subsequent nested array. I.e:

$haystack['my']['string']['is']['nested'] = 'Hello';
$var = 'my@string@is@nested';
$items = explode('@', $var);
$val = $haystack;
foreach($items as $key){
    $val = $val[$key];
}
echo $val;

Note that this does no checking, you likely want to check that $val[$key] exists.

Example here: http://codepad.org/5ei9xS91

Upvotes: 2

Related Questions