0

I have the following array:

$myArray = array(0=>'Zero',
             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.

3 Answers 3

1

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.

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

2 Comments

Hi i dont think there are any refernces inside my array :)
Strange, there seemed to be one. Try using var_dump on $newArray. The last array under the key 'Four' will be a reference (["Four"]=> &array(0) ). Am I missing something there?
1

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 =)

Comments

0
$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.

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.