I have the following JSON code.
{
"Artikelnr":"1000",
"Vooraad_NL":2.0,
"Voorraad_DE":1.0,
"Voorraad_BE":0.0
}
When I loop through the json with a foreach it loops 4 times. How can I make it loop only through the amount of articles. Like 1 article loops only once. When there are 3 articles in the json loop three times.
I use the following php code:
$data = json_decode(file_get_contents('php://input'), true);
if ((isset($data) && $data != "") && (json_last_error() === JSON_ERROR_NONE)) {
foreach ($data as $key => $val) {
$articlenumber = $data['Artikelnr'];
$voorraad_nl = $data['Vooraad_NL'];
$voorraad_de = $data['Vooraad_DE'];
$voorraad_be = $data['Vooraad_BE'];
}
}
2
Answers
The reason your loop is running four times is that you are looping through the keys in the JSON object, and your JSON object has four key-value pairs. If you want to loop through the articles based on the "Artikelnr" key and its values, then you could probably do this:
You have the following
json
So, when you looping it after
json_decode
, you are getting something like this:So, when you are looping the $data:
The loop is iterating over the
$data
array which contains 4 items and you are not using the$key/$val
inside your loop but the$data
itself so your seeing the same items 4 times.if you have only one
json
then you don’t need to loop, you can simply do the same thing without the loop, for example:If you are not sure whether the result is an array of objects or a single object, you may try something like this:
if you want to use each item as an array then you may convert the object (stdClass) using
(array)
, for example:Same could be possible for the single object, for example: