Reputation: 1730
I would like to convert a list of values such as:
$foo = ['a', 'b', 'c'];
into a list of traversing array keys such as:
$bar['a']['b']['c'] = 123;
How I can create an associative array which keys are based on a set values stored in another array?
Upvotes: 3
Views: 112
Reputation: 47774
Here is another option: Create a temporary parsable string (by extracting the first value, then appending the remaining values as square bracket wrapped strings), call parse_str()
, and set the output variable as $bar
.
Code: (Demo)
$foo = ['a', 'b', 'c'];
$val=123;
parse_str(array_shift($foo).'['.implode('][',$foo)."]=$val",$bar);
// built string: `a[b][c]=123`
var_export($bar);
Output:
array (
'a' =>
array (
'b' =>
array (
'c' => '123',
),
),
)
If that first method feels too hack-ish, the following recursive method is a stable approach:
Code: (Demo)
function nest_assoc($keys,$value){
return [array_shift($keys) => (empty($keys) ? $value : nest_assoc($keys,$value))];
// ^^^^^^^^^^^^^^^^^^--------------------------------------------------------extract leading key value, modify $keys
// check if any keys left-----^^^^^^^^^^^^
// no more keys, use the value---------------^^^^^^
// recurse to write the subarray contents-------------^^^^^^^^^^^^^^^^^^^^^^^^^
}
$foo=['a','b','c'];
$val=123;
var_export(nest_assoc($foo,$val));
// same output
Upvotes: 0
Reputation: 22931
I would do it like this:
$foo = ['a', 'b', 'c'];
$val = '123';
foreach (array_reverse($foo) as $k => $v) {
$bar = [$v => $k ? $bar : $val];
}
We are iterating over the array in reverse and assigning the innermost value first, then building the array from the inside out.
Upvotes: 1
Reputation: 28529
You can make it with reference. Try this code, live demo
<?php
$foo = ['a', 'b', 'c'];
$array = [];
$current = &$array;
foreach($foo as $key) {
@$current = &$current[$key];
}
$current = 123;
print_r($array);
Upvotes: 4