Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

I have a multi dimensional array in PHP

$somearray = array(
    'item1' => array(
        'subitem1' => 'Some value',
        'subitem2' => 'Some other value',
        'subitem3'  => array(
            'subsubitem' => 'A sub value'
        )
    ),
    'item2' => 'a different value'
);

I then have a string map which represents which value I want to select:

"item1/subitem3/subsubitem"

How can I convert from that string map of an array, into:

$wanted_value = $somearray['item1']['subitem3']['subsubitem'];

but keeping in mind the array could be any number of levels deep.

share|improve this question

marked as duplicate by mario, tereško, Bobby, Werner Henze, Tushar Gupta Nov 22 '13 at 16:16

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3  
explode your path, then traverse the array with a recursive function. –  mario Nov 21 '13 at 20:23
    
I don't think it should be recursive –  TobSpr Nov 21 '13 at 20:27
1  
Just for fun: eval('$wanted_value = $somearray["' . str_replace("/",'"]["',$map) . '"];'); Done! But seriously, use @TobSpr's method. =) –  jszobody Nov 21 '13 at 20:34
    
well, that's at least creative :P –  TobSpr Nov 21 '13 at 20:35

2 Answers 2

up vote 1 down vote accepted

Another way (should also check to make sure the keys exists):

$path   = explode("/", "item1/subitem3/subsubitem");
$result = $somearray;

foreach($path as $k) {
    $result = $result[$k];
}
echo $result;
share|improve this answer
    
I actually used this over @TobSpr as I found it easier to add some basic sanity checking with a if (isset($result[$k])) in the process, but both solutions worked perfectly. Thank you all. –  Venison's dear isn't it Nov 21 '13 at 21:02

This should work:

$parts = explode("/", $map);

$currentData = $somearray;
for ($i = 0; $i < count($parts); $i++) {
    $currentData = $currentData[$parts[$i]];
}

$result = $currentData;
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.