从Rest API获取JSON数据

Mxk*_*ert 2 php api json for-loop

我正在使用Rest API从网站获取数据,我想在我的网上商店中使用这些数据.我之前从未使用过API.

我现在有以下代码:

<?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>";
}
Run Code Online (Sandbox Code Playgroud)

我的问题是它只显示前两个产品,但我选择了9个产品.如果我打印$ retVal,它会输出所有9个产品.

Ana*_*Die 6

这就是为什么我总是喜欢foreach(),如下所示: -

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

注意: -如果更改count($retVal)为,您的代码也可以使用count($retVal['data'])