Insert values inside multidimensional array

In my PHP application, get the results from DB. After processing the results I need to convert the results like below using foreach

Array
(

[1] => Array -----> This is intent 1, this key indicates all intent values which is equal to 1, should belongs to here.

    (
        [0] => Array
            (
                [name] => A
                [indent] => 1 
            )

       [1] => Array
            (
                [name] => B
                [indent] => 1 
            )

    )

[2] => Array
    (
        [0] => Array
            (
                [name] => B
                [indent] => 2 
            )

        [1] => Array
            (
                [name] => A
                [indent] => 2 
            )

    )

[3] => Array
    (
        [0] => Array
            (
                [name] => A
                [indent] => 3 

            )

    )
)

That I have some intent value common, common intent values are stored in array like array(‘1’=> array(array[0],array[1]));.

What I tried is

foreach($results as $data){
        $root_array[$data['intent']] = array($data);
}

This will replace the old array and insert the last intent value which is common.

I get result like below, the intent 1 and intent 2 are replaced with last data

Array
(

[1] => Array 

(


   [0] => Array
        (
            [name] => B
            [indent] => 1 
        )

)

[2] => Array
(

    [0] => Array
        (
            [name] => A
            [indent] => 2 
        )

)

[3] => Array
(
    [0] => Array
        (
            [name] => A
            [indent] => 3 

        )

)
)

Answer

In the loop you must check if the current indent has been initialized. If not then create it, else just append the new data to it.

foreach($results as $data) {
    if (!isset($root_array[$data['indent']])) {
        $root_array[$data['indent']] = array($data);
    } else {
        $root_array[$data['indent']][] = $data;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *