Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array values to nested array with PHP

Tags:

arrays

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?

like image 831
Ben Fransen Avatar asked Jul 07 '26 23:07

Ben Fransen


1 Answers

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

like image 94
Sougata Bose Avatar answered Jul 09 '26 16:07

Sougata Bose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!