Insert values inside multidimensional array Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Insert values inside multidimensional array without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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;
    }
}
We are here to answer your question about Insert values inside multidimensional array - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji