PHP中的foreach对象数组
Posted
技术标签:
【中文标题】PHP中的foreach对象数组【英文标题】:Foreach array of objects in PHP 【发布时间】:2021-04-14 10:24:20 【问题描述】:我正在尝试组合来自两个表的数据以获取然后转换为 JSON 数据。我希望数据格式类似于:
[
"designs" : [
"id": 6,
"product_id": 2,
"sku": "2648",
"size": "5*4",
"materialType": "Aluminum",
,
"id": 7,
"product_id": 2,
"sku": "1234",
"size": "10*4",
"materialType": "Wood",
],
"id": 2,
"category_id": 5,
"product_name": "Restricted Area Sign",
"price": 1000,
"category_name": "Medical Safety"
]
在 Laravel 中使用以下代码:
$products = Product::get();
foreach($products as $key => $val)
$category_name = Category::where(['id' => $val->category_id])->first();
$products[$key]->category_name = $category_name->name;
$attributes=ProductsAttribute::where(['product_id' => $val->id])->get();
foreach($attributes as $attr => $attrValue)
$products[$key][$attr] = $attrValue;
$products = json_decode($products);
return $products;
但我却收到了这样的回复:
[
"0":
"id": 6,
"product_id": 2,
"sku": "2648",
"size": "5*4",
"materialType": "Aluminum",
,
"1":
"id": 7,
"product_id": 2,
"sku": "1234",
"size": "10*4",
"materialType": "Wood",
,
"id": 2,
"category_id": 5,
"product_name": "Restricted Area Sign",
"price": 1000,
"category_name": "Medical Safety"
]
无论如何要使用键而不是具有不同对象的键来推送数组? 谢谢。
【问题讨论】:
【参考方案1】:我做到了:
public function viewProductsApi(Request $request)
$products = Product::get();
foreach($products as $key => $val)
$category_name = Category::where(['id' => $val->category_id])->first();
$products[$key]->category_name = $category_name->name;
$attributes=ProductsAttribute::where(['product_id' => $val->id])->get();
$products[$key]->desings = $attributes;
$products = json_decode($products);
return $products;
【讨论】:
以上是关于PHP中的foreach对象数组的主要内容,如果未能解决你的问题,请参考以下文章