Laravel API嵌套数据遍历报错:foreach参数类型不符问题求助
问题描述
从API获取产品数据,返回结果包含两层嵌套的data结构。使用foreach遍历能部分列出产品,但无法正确访问单个元素,执行Laravel代码时抛出异常:
ErrorException : foreach() argument must be of type array|object, int given
API返回结构:
{ "data": { "data": [ { "id": 101553, "company_id": 730, "category_id": 132288, "brand_id": 39549, "name": "Hh PRODUCT TEST", "remote_category_id": "scarf", "remote_brand_id": "bershka123", "spu": "zb3940823904" }, { "id": 101554, "company_id": 730, "category_id": 132289, "brand_id": 39549, "name": "Hs PRODUCT TEST", "remote_category_id": "scarf", "remote_brand_id": "bershka123", "spu": "zb3940823905" } ], "count": 175, "search": { "category_id": null, "brand_id": null, "company_id": null }, "start": 0, "length": 10 }, "error_code": 0, "message": "" }
Model代码:
public function getProducts($start =0, $length =10, $category_id =null, $brand_id=null, $spu=null, $name=null, $is_active=null, $id=null, $remote_brand_id = null, $remote_category_id=null) { $request = Http::withHeaders([ 'Authorization' => 'Bearer '.$this->jwttoken, 'Content-Type' => 'application/json' ])->post($this->sandbox . 'products/search',[ "start" => $start, "length" => $length, "search" => [ "category_id" => $category_id, "brand_id" => $brand_id, "spu" => $spu, "name" => $name, "is_active" => $is_active, "id" => $id, "remote_brand_id" => $remote_brand_id, "remote_category_id" => $remote_category_id ] ])->json(); return $request; }
Controller代码:
$company_id = 100; $products = (new Client($company_id))->getProducts(); foreach($products as $product){ foreach($product as $prd){ dump($prd); } }
错误原因
Controller代码遍历层级错误:
$products是API返回的完整数组,包含data、error_code、message三个键- 第一层
foreach($products as $product)会依次遍历这三个键对应的value:- 第一个value是
data对应的嵌套对象(包含内层data数组、count等) - 第二个value是
error_code对应的整数0
- 第一个value是
- 当遍历到
error_code时,第二层foreach($product as $prd)试图对整数执行遍历操作,直接触发类型错误。
解决方案
直接定位到第二层data数组(即实际的产品列表)再进行遍历:
修改后的Controller代码:
$company_id = 100; $response = (new Client($company_id))->getProducts(); // 先判断API返回正常,再拿到产品列表 if ($response['error_code'] === 0 && isset($response['data']['data'])) { $products = $response['data']['data']; // 遍历产品列表 foreach($products as $product){ // 访问单个产品元素 dump($product['id']); dump($product['name']); dump($product['spu']); // 或者直接打印整个产品 // dump($product); } }
额外优化建议
可以在Model的getProducts方法里直接返回内层的产品数组,简化Controller逻辑:
// Model中修改返回逻辑 public function getProducts(...) { $request = Http::...->json(); // 直接返回产品列表,异常情况返回空数组 if ($request['error_code'] === 0) { return $request['data']['data']; } return []; } // Controller中直接使用 $products = (new Client($company_id))->getProducts(); foreach($products as $product){ // 处理产品 }
内容的提问来源于stack exchange,提问作者Ontrable
相关产品推荐
相关产品推荐

