-2

What is the best way to achieve the following? I.e. building the array keys from another array dynamically?

$array = (
    'key1',
    'key2',
    'key3'
);

Resulting in:: $arr['key1']['key2']['key3'] = array()/value;

So in other words the more values you add to $array (and or less) then the corresponding mulitidensional array is built up.

Thanks

Antony
  • 3,875
  • 30
  • 32
  • 1
    What happened to `first` and `second`. What do you mean `= true`? – Madbreaks Nov 12 '14 at 20:28
  • I've edited my question - good point :) – Antony Nov 12 '14 at 20:30
  • 1
    Better but, what does `= array()/value;` mean? – Madbreaks Nov 12 '14 at 20:34
  • your edited question makes no sense. You're asking about building an array off another, but only show a single array, then at the end of your question you talk about multidimensional arrays, which wasn't even a thing at the start of your question =) – Mike 'Pomax' Kamermans Nov 12 '14 at 20:34
  • All he needs is an array with keys that represent the values of another array. My question would be why? Explain more, maybe things can be done in a different way. – RST Nov 12 '14 at 20:36
  • The reason is because I'm trying to build a tree of array values so each key is added onto the parent. I don't mind what array()/value is - that is there as an example. I will be adding that value myself. The multidimensional bit was there at the beginning and by having all the keys that is what you would be building. I am also working on a solution at the moment unless there is a really obvious way I'm missing. – Antony Nov 12 '14 at 20:39

2 Answers2

0

You could easily build a recursive function, or I use a reference:

$array = array('key1', 'key2', 'key3');

$result = array();
$temp = &$result;

foreach($array as $key) {
    $temp =& $temp[$key];
}
$temp = 'value'; //or whatever

var_dump($result);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
0

I'd already started, so I'll post my answer even though there's already an accepted answer:

$input = array('key1', 'key2', 'key3');
$result = array();

buildArray($input, $result);
print_r($result);

function buildArray($input, &$result){
    if(0 == count($input))
        return $result;

    $next = array_shift($input);
    $result[$next] = array();
    buildArray($input, $result[$next]);
}

Works, though I think the answer posted by @AbraCadaver is more elegant.

Madbreaks
  • 19,094
  • 7
  • 58
  • 72