【发布时间】:2019-11-17 16:07:47
【问题描述】:
第一次来这里,是个潜伏者,搜索了很多,但这次遇到了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
}
]
}
]
希望它能为每个数组生成循环结果。
【问题讨论】:
-
如果是
collection,您是否尝试过:$location[0]->get(0)->location_id? -
您最好将
$location数组创建为记录数组,目前它是一个集合数组(其中包含一个数组)。 -
@dWinder 哦,谢谢,我试过了,但我得到“调用未定义的方法 stdClass::get()”
-
能否请您添加
$locations的var_dump(在循环之后)?
标签: php arrays multidimensional-array laravel-5.7