来自数组json数据的Foreach

时间:2018-01-10 10:28:41

标签: php arrays json

我得到了一个JSON格式的数组,我解码了这些数据。通过选择例如,我可以访问单个数据echo $ myArray [0] [" name"]; 但是,我想循环迭代数组中的所有名称和价格。你能支持我在我的代码中找到错误吗?

$url = "myurl";
$response = file_get_contents($url);
$myArray = json_decode($response, true);


foreach ($myArray as $product) {
    echo $product->name . '<br>';
}

这是一个数组示例:

[{
    "id": 782,
    "name": "Test Translation New",
    "price": "1",
    "image": {
        "url": "xxx/image-2.jpg",
        "position": 0
    },
    "link": "https:xxx",
    "nickname": "newmarker"
}, {
    "id": 777,
    "name": "Test Translation",
    "price": "0",
    "image": {
        "url": "https:xxx/image-1.jpg",
        "position": 0
    },
    "link": "https:xxx",
    "nickname": "newmarker"
}]

3 个答案:

答案 0 :(得分:0)

您正在使用json_decode(..., true),因此返回的$myArray是一个数组,其所有子项都是数组。

<?php
$response = '
[{
    "id": 782,
    "name": "Test Translation New",
    "price": "1",
    "image": {
        "url": "xxx/image-2.jpg",
        "position": 0
    },
    "link": "https:xxx",
    "nickname": "newmarker"
}, {
    "id": 777,
    "name": "Test Translation",
    "price": "0",
    "image": {
        "url": "https:xxx/image-1.jpg",
        "position": 0
    },
    "link": "https:xxx",
    "nickname": "newmarker"
}]
';

$myArray = json_decode($response, true);

foreach ($myArray as $product) {
    echo $product['name'] . "<br>\n";
}

输出:

Test Translation New<br>
Test Translation<br>

答案 1 :(得分:0)

如果给出了json_decode的第二个参数并且它是true,则返回的结构是一个关联数组。话虽如此,您可以打印名称和价格,如:

foreach ($myArray as $product) {
    echo $product['name'] . ' - ' . $product['price'] .  '<br>';
}

答案 2 :(得分:-1)

如果给出了json_decode的第二个参数且它为真,则返回的结构是一个关联数组。话虽如此,您可以打印名称和价格,如:

foreach ($myArray as $product) {
  echo $product['name'];
  echo (int) $product['price'];
}

或者您也可以

foreach ($myArray as $product) {
  echo "{$product['name']} - {$product['price']} <br />";
}