How to create a nested array from collection with parent IDs in laravel?

  laravel

I want to create a nested array which maintain parent child relations by using their parent_id.I want to make the following query results into nested array.

$catItems= ProductCategory::all()->toArray();
        $source = array();
        foreach($catItems as $key => $value) {
            $source[$key] = $value;
        } 

the following method I applied to create nested array

$nested = array();
     
        foreach ($source as &$s) {
            if(is_null($s['parent_id']) ) {
                // no parent_id so we put it in the root of the array
                $nested[] = &$s;
            }
            else {
                $pid = $s['parent_id'];
                if ( isset($source[$pid])) {
                    // If the parent ID exists in the source array
                    // we add it to the 'children' array of the parent after initializing it.
     
                    if ( !isset($source[$pid]['children']) ) {
                        $source[$pid]['children'] = array();
                    }
                    $source[$pid]['children'][] = &$s;
                }
            }
        }

If i do dd($source) i am getting the following output

 array:3 [▼
      0 => array:8 [▼
        "id" => 5
        "name" => "Electronics"
        "status" => 1
        "parent_id" => null
        "created_by" => 1
        "updated_by" => null
        "created_at" => "2021-05-06T06:32:37.000000Z"
        "updated_at" => "2021-05-06T06:32:37.000000Z"
      ]
      1 => array:8 [▼
        "id" => 6
        "name" => "tv"
        "status" => 1
        "parent_id" => 5
        "created_by" => 1
        "updated_by" => null
        "created_at" => "2021-05-06T06:33:00.000000Z"
        "updated_at" => "2021-05-06T06:33:00.000000Z"
      ]
      2 => array:8 [▼
        "id" => 7
        "name" => "Home appliances"
        "status" => 1
        "parent_id" => null
        "created_by" => 1
        "updated_by" => null
        "created_at" => "2021-05-06T06:33:16.000000Z"
        "updated_at" => "2021-05-06T06:33:16.000000Z"
      ]
    ]

If i do dd($nested) i am getting the only parent array like bellow :

array:2 [▼
  0 => & array:8 [▼
    "id" => 5
    "name" => "Electronics"
    "status" => 1
    "parent_id" => null
    "created_by" => 1
    "updated_by" => null
    "created_at" => "2021-05-06T06:32:37.000000Z"
    "updated_at" => "2021-05-06T06:32:37.000000Z"
  ]
  1 => & array:8 [▼
    "id" => 7
    "name" => "Home appliances"
    "status" => 1
    "parent_id" => null
    "created_by" => 1
    "updated_by" => null
    "created_at" => "2021-05-06T06:33:16.000000Z"
    "updated_at" => "2021-05-06T06:33:16.000000Z"
  ]
]

Source: Laravel

Leave a Reply