Getting JSON data from Rest API

Viewed 817

I am using a Rest API to get data from a website and I would like to use that data in my webshop. I have never worked with API's before.

I now have the following code:

<?php 

$url = 'https://api.floraathome.nl/v1/products/get?apitoken=[MY_API_TOKEN]&type=json';
$json = file_get_contents($url);
$retVal = json_decode($json, TRUE);

for ($x = 0; $x < count($retVal); $x++) {
    echo $retVal['data'][$x]['dutchname']."<br>";
    echo $retVal['data'][$x]['purchaseprice']."<br>";
    echo $retVal['data'][$x]['promotionaltext']."<br><br>";
}

My problem is that it only shows the first 2 products, but I have 9 products selected. If I print $retVal, it does output all 9 products.

2 Answers

That's why i always prefer foreach(), do like below:-

foreach($retVal['data'] as $retV){
    echo $retV['dutchname']."<br>";
    echo $retV['purchaseprice']."<br>";
    echo $retV['promotionaltext']."<br><br>";
}

Note:- your code will also work if you change count($retVal) to count($retVal['data'])

My problem is that it only shows the first 2 products, but I have 9 products selected. If I print $retVal, it does output all 9 products.

Thats because you are looping over the wrong count of your elements:

for ($x = 0; $x < count($retVal); $x++)
                  ^^^^^^^^^^^^^^

as you can see, the problem is in here count($retVal) which I assume that the structure is like something like that:

Array (
    [data] => Array ()
    [xxxx] => 'xx'
)

so to solve this, -and if you want to go with for loop rather than the other right solution using foreach- you will need to get the prober count count($retVal['data']):

for ($x = 0; $x < count($retVal['data']); $x++) {
    echo $retVal[$x]['dutchname']."<br>";
    echo $retVal[$x]['purchaseprice']."<br>";
    echo $retVal[$x]['promotionaltext']."<br><br>";
}
Related