3 回答

TA貢獻(xiàn)1872條經(jīng)驗(yàn) 獲得超4個(gè)贊
根據(jù)您問(wèn)題中的數(shù)據(jù),我猜測(cè)$item您的循環(huán)中等于
{
"product_id": 2,
"product_name": "xyz",
},
在這種情況下,您所需要做的就是添加$productImagedata['image']為數(shù)組中的鍵,同時(shí)引用$item.
像這樣替換你的循環(huán):
//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貢獻(xiàn)1793條經(jīng)驗(yàn) 獲得超6個(gè)贊
merge 方法將給定的數(shù)組或集合與原始集合合并。如果給定項(xiàng)目中的字符串鍵與原始集合中的字符串鍵匹配,則給定項(xiàng)目的值將覆蓋原始集合中的值:
$collection = collect(['product_id' => 1, 'price' => 100]);
$merged = $collection->merge(['price' => 200, 'discount' => false]);
$merged->all();
// ['product_id' => 1, 'price' => 200, 'discount' => false]

TA貢獻(xiàn)1834條經(jīng)驗(yàn) 獲得超8個(gè)贊
那應(yīng)該有效
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 關(guān)注
- 174 瀏覽
添加回答
舉報(bào)