I'm getting some data via api as json:
Response headers:
200 success
access-control-allow-credentials: true
access-control-allow-headers: accept, origin, x-requested-with, authorization, content-type
access-control-allow-methods: OPTIONS, GET, POST, PUT, DELETE
access-control-allow-origin: *
cache-control: no-store, no-cache, must-revalidate
content-length: 1046
content-type: application/json; charset=utf-8
date: Sun, 25 Jul 2021 14:14:51 GMT
expires: Thu, 19 Nov 1981 08:52:00 GMT
pragma: no-cache
server: nginx
x-vendon-api-requests: 2
Response data:
{
"code": 200,
"result": {
"id": 3075531,
"stock_id": 184445,
"stock_article": "Parfum 2 ml 047 women",
"selections": [
{
"selection": 11,
"label": "11",
"price": 1,
"pricelist": null,
"pricelist_type": null,
"payment_device_type": null
}
],
"type": "PRODUCT",
"name": "Parfum 2 ml 047 women",
"units": null,
"amount": 10,
"amount_max": 11,
"amount_standart": 11,
"amount_critical": 3,
"refill_unit_size": 1,
"min_refill": 1,
"refillable": true,
"last_purchase": 1624011420,
"currency": "EUR",
"recipe": [],
"ingredient_line": null,
"critical": false,
"extraction_time_enabled": null,
"min_extraction_time": null,
"max_extraction_time": null,
"product_price_group": null,
"has_route_planing_expiry_date": false
}
}
Then decoding and doing foreach()
to output only variable that i need with:
code
$decodedJson = json_decode($html, true);
foreach($decodedJson as $answer) {
echo 'Item:' .$answer['name'].' available '.$answer['amount'].'pcs.';
}
But i'm stuck, cos getting duplicates in output(echo row without variable, than echo row with variable, can't fix this, can someone help?
Output
Item: available pcs.Item:Parfum 2 ml 047 women available 10pcs.
My Answer:
"items": [
{
"id": 1,
"name": "Item 1"
},
{
"id": 2,
"name": "Item 2"
},
{
"id": 3,
"name": "Item 3"
}
]
}_I want to loop through the "items" array and echo out the "id" and "name" of each item. Here's how you can do it in PHP:_
php
// JSON response data
$responseData = '{
"items": [
{
"id": 1,
"name": "Item 1"
},
{
"id": 2,
"name": "Item 2"
},
{
"id": 3,
"name": "Item 3"
}
]
}';
// Decode JSON data
$data = json_decode($responseData, true);
// Loop through items array
foreach ($data['items'] as $item) {
// Echo out id and name without using a variable
echo "ID: " . $item['id'] . ", Name: " . $item['name'] . "
";
// Echo out id and name using a variable
$id = $item['id'];
$name = $item['name'];
echo "ID: $id, Name: $name
";
}
?>
This code will output the following:
ID: 1, Name: Item 1
ID: 1, Name: Item 1
ID: 2, Name: Item 2
ID: 2, Name: Item 2
ID: 3, Name: Item 3
ID: 3, Name: Item 3
Rate this post
3 of 5 based on 3091 votesComments