-1

Edit (after downvote): There is a similar question here > Using a string path to set nested array data However I didn't find that question when searching for an answer due to the way it's worded, and I'm sure this will happen for other people, so this question may act as a useful gateway to that question and it's answers.

I'm sure I'm missing something obvious, but I can't think how to do this: I have an array containing one or more items:

array('value1', 'value2');

I need to use these values as the keys in a multidimensional array :

array['value1']['value2'] = 'somevalue';

How do I do this?

greebstreebling
  • 316
  • 1
  • 2
  • 13

1 Answers1

0

You can use a nice recursion here:

function nestArray($items, $value) {
    return $items ?
        array($items[0] => nestArray(array_slice($items, 1), $value))
        : $value;
}

$array = array('value1', 'value2');
print_r(nestArray($array, 'somevalue'));
HTMHell
  • 5,761
  • 5
  • 37
  • 79