php - 如何在 laravel 中回显这个多维集合
问题描述
第一次来这里,潜伏并搜索了很多,但这次Laravel
收藏有问题。试图回显foreach
这个多维集合数组,但我不知道如何。
我已经尝试改变很多方式来展示我所知道的。但无济于事,希望得到一些见解,可能会改变我的方法或其他东西......
从数据库获取的代码
$l = [];
for($i = 0; $i < count($request->products); $i++){
$l[] = [
'locaction_id' => $request->products[$i]['location'],
];
$locations[] = DB::table('locations')->select('*')->whereIn('location_id',$l)->get();
};
用于显示数组的代码,尝试了两者$location->stuff
并$location[0][0]['location_id']
出现错误
$location->location_id
,输出错误:
无法找到 location_id。
$location[0][0]['location_id']
并$location['location_id']
给出:
StdClass 错误或找不到 location_id。
foreach($locations as $key => $location){
echo $key. " -" .$location->location_id. "<br>";
};
从数据库返回的数组
array:2 [▼
0 => Collection {#662 ▼
#items: array:1 [▼
0 => {#660 ▼
+"location_id": 1
+"loc_name": "A0001"
+"loc_desc": "Cabinet A North"
+"created_at": "2019-07-05 10:31:12"
+"updated_at": null
}
]
}
1 => Collection {#688 ▼
#items: array:1 [▼
0 => {#686 ▼
+"location_id": 1
+"loc_name": "A0001"
+"loc_desc": "Cabinet A North"
+"created_at": "2019-07-05 10:31:12"
+"updated_at": null
}
]
}
]
希望它能为每个数组产生循环结果。
解决方案
你可以像这样改变你的方法,
// first fetch all location ids in array
$locationIds = array_column($request->products, "location");
// pass all location ids to fetch data
$locations = DB::table('locations')->select('*')->whereIn('location_id', $locationIds)->get();
// do foreach loop to fetch that data
foreach($locations as $key => $location){
echo $key. " -" .$location->location_id. "<br>";
}
如果由于某种原因您正在编写代码段,
for ($i = 0; $i < count($request->products); $i++) {
$l = $request->products[$i]['location'];
// I change it to first instead of get
$locations[] = DB::table('locations')->select('*')->where('location_id', $l)->first();
}
// do foreach loop to fetch that data
foreach ($locations as $key => $location) {
echo $key . " -" . $location->location_id . "<br>";
}
推荐阅读
- sass - scss中的双连字符是什么?
- java - 给定 javaClass 'class com.google.gson.JsonObject' 映射到 ValueType,预期 ManagedType
- angular - Turbo Table:无法通过单击复选框来选择行
- mysql - mysql查询在多个字段中显示相同的值
- c# - 带有社交登录的 ASP.NET MVC C# OWIN 令牌身份验证
- maven - 使用 JIB 插件对多模块 Spring Boot 应用程序进行 Dockerizing
- c# - 将来自 TextContext.Error.WriteLine() 的数据放在 NUnit 默认结果写入器的输出开头
- javascript - 是否有通过端点提供完全包含的 Web 组件的名称?
- reactjs - 异步/等待内部承诺
- vb.net - 创建前景插件