1

there's an array A,which has a variable number of values. I want to convert values of array A to an index of array B.

Language: PHP

Example:

//array A
$a={'a','b','c','d'};

//converted to an index of array B
$b['a']['b']['c']['d']='somevalue';

The problem is that the number of values of array A is flexible.

Is there a way out? Thanks.

2 Answers 2

1
$a=['a','b','c','d'];

$b = [];
$c = &$b;
foreach($a as $key) {
    $c[$key] = $c;
    $c = &$c[$key];
}
$c = 'somevalue';
unset($c);

var_dump($b);

Demo

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for so quick an answer . I tested this code and got an unexpected result : array(1) { ["a"]=> array(2) { ["a"]=> array(1) { ["a"]=> RECURSION } ["b"]=> array(3) { ["a"]=> array(1) { ["a"]=> RECURSION } ["b"]=> array(2) { ["a"]=> array(1) { ["a"]=> RECURSION } ["b"]=> RECURSION } ["c"]=> ...........
0

Thanks to @Mark Baker. I modified some code and it works.

$a = array('a', 'b', 'c', 'd');

$b = array();

rsort($a);

$i = 0;
foreach ($a as $v)
{
    if ($i++ > 0)
    {
        $c = array();
        $c[$v] = $b;
        $b = $c;
    }
    else
    {
        $b[$v] = 111;
    }
}

var_dump($b);

Result,what I want exactly :

array(1) {
  ["a"]=>
  array(1) {
    ["b"]=>
    array(1) {
      ["c"]=>
      array(1) {
        ["d"]=>
        int(111)
      }
    }
  }
}

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.