i am getting product data from API end. there are two nested "data" in the incoming array. i can list the products with foreach, but I can't reach a single element. when I try a few methods, it returns errors like "array,object int". Where am I going wrong and how can I access its elements?
the method i'm trying now is this and i'm applying this process on the Laravel side.
{
"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);
}
}
Result:
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() argument must be of type array|object, int given
How do i get the correct loop format and elements?
CodePudding user response:
You have to loop like this way
foreach($products["data"]["data"] as $product)
{
dump($product);
}