0

I'm trying to figure out how should I populate the array in below format. Tried several times with while and for loop to store and remove found id but still couldn't figure it out.

This is what I have tried.

$filtered_list = array();
        $unfiltered_list = array(1);
        while(count($unfiltered_list) > 0)
        {
            $found_id_list = array();
            foreach ($unfiltered_list as $ul_obj)
            {
                foreach ($list as $l_obj) 
                {
                    if($list[$l_obj->sub_id] == $ul_obj)
                    {
                        $temp_id = $list[$l_obj->id];
                        $found_id_list[] = $temp_id;

                        if($filtered_list[$temp_id]==null)
                        {
                            $filtered_list[$temp_id] = array();
                        }

                        $filtered_list[$temp_id][] = $l_obj;
                    }
                }
            }

            $unfiltered_list = $found_id_list;
        }

        json_encode($filtered_list);

The idea is to map the "sub_id" field in the object to the "id" and so on for the nested ones. Sorry that my Maths is not so good, but may I know is it possible to convert the list into this format?

Here's an example of an array.

list = [{"id":1,"sub_id":0,"name":"a"}, {"id":2,"sub_id":1,"name":"b"}, {"id":3,"sub_id":1,"name":"c"}, {"id":4,"sub_id":2,"name":"d"}, ...]

And with the above array i'm trying to convert into below json format.

[{"name":"a", "id":1, "list":[ 
            {"name":"b", "id":2, "list": [ 
                {"name":"d", "id":4}, 
                {"name":"e", "id":5}
            ]}, 
            {"name":"c", "id":3, "list": [
                {"name":"f", "id":6}
            ]} 
     ]}]
XiaoEpic
  • 1
  • 3

0 Answers0