3 回答
TA贡献1872条经验 获得超3个赞
根据您问题中的数据,我猜测$item您的循环中等于
{
"product_id": 2,
"product_name": "xyz",
},
在这种情况下,您所需要做的就是添加$productImagedata['image']为数组中的键,同时引用$item.
像这样替换你的循环:
//notice the `&` sign on `$item`. This means we are referencing that variable,
//which basically means that if you change it in the loop, it changes the original as well.
foreach ($products as &$item)
{
//create image object
$image_data = DB::table('product_image')->where('product_id', $item->product_id)->get();
//add image object to `$item` object
$item->image = $image_data;
}
TA贡献1793条经验 获得超6个赞
merge 方法将给定的数组或集合与原始集合合并。如果给定项目中的字符串键与原始集合中的字符串键匹配,则给定项目的值将覆盖原始集合中的值:
$collection = collect(['product_id' => 1, 'price' => 100]);
$merged = $collection->merge(['price' => 200, 'discount' => false]);
$merged->all();
// ['product_id' => 1, 'price' => 200, 'discount' => false]
TA贡献1834条经验 获得超8个赞
那应该有效
public function get_products()
{
$products = DB::table('products')->get();
$arr = [];
foreach ($products as $item) {
$productImageData['image'] = DB::table('product_image')->where('product_id', $item->id)->get()->toArray();
$arr = array_combine($arr, $productImageData);
}
$pageData = collect(['products' => $products]);
$data = collect(['status' => [
'code' => '100',
'message' => 'Success',
'data' => $pageData]]);
return response()->json($data);
}
- 3 回答
- 0 关注
- 142 浏览
添加回答
举报