开发者

PHP Creating Dynamic Mulidimensional Arrays

I have the following array:

$myArray = array(0=>'Zero',
 开发者_JS百科            1=>'One',
             2=>'Two',
             3=>'Three',
             4=>'Four');

And i would like it in the following format:

$newArray = array('One'=>
                array('Two'=>
                   array('three'=>
                      array('four'=>
                         array('five'=>
                            array())))));

This could be infinite levels although more realistically about 1-6 levels deep.


Something like this should do:

$myArray = array(0=>'Zero',
     1=>'One',
     2=>'Two',
     3=>'Three',
     4=>'Four');

$myRecursiveArray = array();
$l = count($myArray);
for($i = $l; 0 < $i; --$i)
{
    $myRecursiveArray = array($myArray[$i - 1]=> $myRecursiveArray);
}

yes123 has a shorter answer, but it leaves a reference in your array. Could have no impact if it's what you need.


Sorted it this morning, aparently the answer was sleep!

heres my solution

$myNewArray = array();
$myArray = explode('->',"Zero->One->Two->Three");
$myArray = array_reverse($myArray);

foreach($myArray as $key => $value) {
    $myTempArray = $myNewArray;
    unset($myNewArray);
    $myNewArray[$value] = $myTempArray;
}

Thanks for the answers, comments on my solution are welcome =)


$newArray=array();
$current = &$newArray;
foreach($myArray as $v) {
   $current[$v] = array();
   $current = &$current[$v];
}

Watch it live & free here: http://codepad.org/utESnGiv
Insuperable 4 lines of code.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜