3

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?

7
  • Have you tried something? Post your effort too. Commented Dec 18, 2017 at 7:14
  • You can use a for loop to achieve that. Commented Dec 18, 2017 at 7:19
  • 1
    Where does the 123 come from? If the input was ['a', 'b', 'c', 'd']; would that make the output $bar['a']['b']['c']['d']? And would it still be 123? Or 1234? Commented Dec 18, 2017 at 7:20
  • The value '123' would be set at the end very end after creating the keys of the array Commented Dec 18, 2017 at 7:23
  • 1
    Similar with this one string to associative array conversion Commented Dec 18, 2017 at 7:24

3 Answers 3

4

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.