从json数组中获取数据 - 未定义的索引错误

时间:2015-01-05 05:45:02

标签: php json

以下是json响应,我在获取shipping_address数据时遇到问题。

{
    "orders": [{
        "created_at": "2015-01-04T02:20:03+01:00",
        "financial_status": "paid",
        "id": 384536708,
        "total_price": "45.00",
        "line_items": [{
            "fulfillment_service": "manual",
            "fulfillment_status": null,
            "gift_card": false,
            "grams": 0,
            "price": "45.00",
            "quantity": 1,
            "requires_shipping": true,
            "taxable": true,
            "title": "test",
            "vendor": "test",
            "name": "test",
            "properties": [],
            "product_exists": true,
            "fulfillable_quantity": 1,
            "tax_lines": []
        }],
        "shipping_address": {
            "address1": "Street 20",
            "address2": "",
            "city": "City",
            "company": "",
            "country": "USA",
            "first_name": "Name",
            "last_name": "Surname",
            "latitude": 45.000000,
            "longitude": 10.000000,
            "phone": "",
            "province": "",
            "zip": "12345",
            "name": "Name Surname",
            "country_code": "US",
            "province_code": null
        }
    }, [...]

我可以通过此代码获得订单:

$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['orders'] as $order){
    echo "<td>".$order['id']."</td>";
}

但是当我尝试获取 shipping_address 这样的数据时:

foreach ($json['shipping_address'] as $sa) {
    echo "<td>".$sa['name']."</td>";
}

然后我得到:注意:未定义索引:shipping_address 警告:为foreach()提供的参数无效

我的目标阵列是错误的吗?

3 个答案:

答案 0 :(得分:0)

应该是 -

foreach ($json['orders']['shipping_address'] as $sa) {

试试这个 -

foreach($json['orders'] as $order){
    echo "<td>".$order['id']."</td>";
    echo "<td>".$order['shipping_address']['name']."</td>";
}

答案 1 :(得分:0)

foreach ($json['orders']['shipping_address'] as $sa) {

    echo "<td>".$sa['name']."</td>";
}

答案 2 :(得分:0)

试试这个:

$content = file_get_contents($url);
$json    = json_decode($content, true);

foreach($json as $orders){
    foreach($orders as $odarr){
        foreach($odarr['shipping_address'] as $shipadd){
            echo $shipadd['address1'];
        }
    }
}