0

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 

        )

)
)

1 Answer 1

2

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;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for your answer.

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.