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


Get data from json array - Undefined index error

下面是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() 提供的参数无效

我的目标阵列有误吗?

应该是 -

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

试试这个——

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

试试这个:

$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'];
        }
    }
}