我正在從 API 端獲取產品資料。傳入陣列中有兩個嵌套的“資料”。我可以用 foreach 列出產品,但我無法達到單個元素。當我嘗試幾種方法時,它會回傳諸如“array,object int”之類的錯誤。我哪里出錯了,我該如何訪問它的元素?
我現在正在嘗試的方法是這個,我正在 Laravel 端應用這個程序。
{
"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": ""
}
模型:
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;
}
控制器
$company_id = 100;
$products = (new Client($company_id))->getProducts();
foreach($products as $product){
foreach($product as $prd){
dump($prd);
}
}
結果:
0 => array:27 [
"id" => 101530
"company_id" => 730
"category_id" => 132047
"brand_id" => 39316
"name" => "Hs Test Shoe"
"remote_category_id" => "5a39b114f1ff6e42639e9e041cd002d6"
"remote_brand_id" => "617392d2b51dbba1a2e5561a3e4eefe7"
"spu" => "845504"
],
1 => array:36 [
"id" => 231303
"company_id" => 730
"product_id" => 101530
"supplier_id" => null
"remote_supplier_id" => null
"name" => "Hd Test Shoe"
"description" => "This is a test product."
"sku" => "2K4F9966WHITE42"
]
ErrorException : foreach() 引數的型別必須是陣列|物件,給定的 int
如何獲得正確的回圈格式和元素?
uj5u.com熱心網友回復:
你必須像這樣回圈
foreach($products["data"]["data"] as $product)
{
dump($product);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/505180.html
上一篇:帶有nginx的Dockerizedreactsocket.io客戶端已連接但未發送到反向代理uvicornasgi服務器(客戶端到服務器,反之亦然)
下一篇:在GAS中運行cURL
