Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating nested parent child array from one dimensional array in php

Tags:

arrays

php

I have 2 array.

First Array:

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

Second Array:

 $array =  Array
    (
        [a] => Array
            (
                [0] => b
                [1] => h
            )

        [b] => c
        [c] => d
        [h] => m
    )

i need to change this array like

First array:

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

                )

        )

)

Second Array:

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

                        )

                )

            [h] => Array
                (
                    [m] => Array
                        (
                        )

                )

        )

)

sirwilliam answers helped for first array problem. and I need it for multi dimensional array. Help to resolve the problem. Thanks in advance

like image 997
Jegan Avatar asked Jun 10 '15 12:06

Jegan


1 Answers

You can try to use & (references):

PHP:

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

    $newArray = array();
    $newArray[key($array)] = array();
    $part = &$newArray;

    foreach($array as $first => $second){
        $part = &$part[$first];
        $part[$second] = array();
    }

    echo "<pre>";
    print_r($newArray);
    echo "</pre>";

?>

Result:

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

                        )

                )

        )

)

Then you can create a loop for the last part.

like image 92
botenvouwer Avatar answered Oct 16 '22 01:10

botenvouwer