Ad

Issue Creating JSON Feed In Laravel

- 1 answer

I am trying to create a JSON feed using two arrays of data in the format mentioned below.

{ 
   "items":[ 
      { 
         "category_id":1,
         "category_name":"Mens Clothing",
         "child":[ 
            { 
               "product_id":1,
               "product_name":"Shirts"
            },
            { 
               "product_id":2,
               "product_name":"T-Shirts"
            }
         ]
      }
   ]
}

However, I am getting like the following.

{ 
   "items":[ 
      { 
         "category_id":1,
         "category_name":"Mens Clothing",
         "child":[ 

         ]
      }
   ],
   "child":[ 
      { 
         "product_id":1,
         "product_name":"Shirts"
      },
      { 
         "product_id":2,
         "product_name":"T-Shirts"
      }
   ]
}

I have written the following in Laravel.

$data = [
    'items' => [],
];

foreach ($categories as $key => $category) {
    $data['items'][$key] = [
        'category_id' => $category->id,
        'category_name' => $category->category_name,
        'child' => [],
    ];
}

foreach ($products as $key => $product) {
    $data['child'][$key] = [
        'product_id' => $product->id,
        'product_name' => $product->product_name
    ];
}

Can anyone please help me figure out this issue?

Ad

Answer

If product has 'category_id' - something like the following can work:

$data = [
    'items' => [],
];

foreach ($categories as $key =>  $category) {
    $children = [];
    foreach ($products as $key => $product){
        if($product->category_id == $category->id) {
            $children[] = $product;
        }
    }
    $data['items'][$key] = [
        'category_id' => $category->id,
        'category_name'=> $category->category_name,
        'child' => $children,
    ];
}
Ad
source: stackoverflow.com
Ad