简体   繁体   中英

Loop through Categories and its Products in PHP Laravel

I have to create an array with the categories array and its related products i'm fetching category with all related products using this query

  $categoryData= Category::with('product')->get();

Data is beign fetched properly, using this loop to get data in the format given below:

 foreach($categoryData as $row){
            $categoriesData[] = [
                'id' => $row->id,
                'title' =>  $row->title,
            ];
          foreach($row->product as $rowproduct){
            $categoriesData['product_details'][] = [
             'product_name' => $rowproduct->name,
             'product_price' => $rowproduct->price
      ];
}
}

Format (It should be something like this):

{
    "categoriesData": {
        "0": {
            "id": 1,
            "category_name" : "Name 1",
        "product_details": [
            {
                "id": 1,
                "product_name": Product Name,
            },
        ],
        "1": {
            "id": 2,
            ""category_name" ": "Name 2",
            "product_details": [
            {
                "id": 1,
                "product_name": product name,
            },
        },
      
   

but through present loop all product is getting saved in one array. It is not saving inside category.

Any help is highly appreciated

You can do this with Collection methods if you wanted to, basically just map :

$array = $categoryData->map(function ($category) {
    return [
        'id' => $category->id,
        'title' => $category->title,
        'product_details' => $category->products->map(function ($product) {
            return [
                'product_name' => $product->name,
                'product_price' => $product->price,
            ];
        }),
    ];
})->all();

Though this is going in the direction of using a transformer or API resource to format this data.

Hi I think this is what you're looking for:

foreach ($categoryData as $key => $row) {
    $categoriesData[$key] = [
        'id' => $row->id,
        'title' => $row->title,
    ];
    foreach ($row->product as $rowproduct) {
        $categoriesData[$key]['product_details'][] = [
            'product_name' => $rowproduct->name,
            'product_price' => $rowproduct->price
        ];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM