开发者

Add elements to sub-array recursively

开发者 https://www.devze.com 2023-01-28 02:50 出处:网络
I\'m trying to add elements to a sub array of the sub array where they were added in the previous iteration, i.e. transforming this:

I'm trying to add elements to a sub array of the sub array where they were added in the previous iteration, i.e. transforming this:

$a = array('a', 'b', 'c');开发者_开发技巧

Into this:

$new_array = array(
    'a' => array(
        'b' => array(
            'c' => array()
        )
    )
);


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

$tmp = array_reverse($a);

$new_array = array();
foreach ($tmp as $item) { $new_array = array($item => $new_array); }


function makeArrayChain($chain)
{
    $key = array_shift($chain);

    if ($key === NULL) {
        return array();
    } else {
        return array($key => makeArrayChain($chain));
    }
}

var_dump(makeArrayChain(array('a', 'b', 'c'));

array(1) {
  ["a"]=>
  array(1) {
    ["b"]=>
    array(1) {
      ["c"]=>
      array(0) {
      }
    }
  }
}


Similar to @aibs solution.

<?php

function splitIntoSubArray($array) {
  return $array ? array(array_shift($array) => splitIntoSubArray($array)) : array();
}

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

print_r(splitIntoSubArray($a));

Output:

Array
(
    [a] => Array
        (
            [b] => Array
                (
                    [c] => Array
                        (
                        )

                )

        )

)
0

精彩评论

暂无评论...
验证码 换一张
取 消