解析JSON时,定位同一标签的特定实例

时间:2015-11-20 15:09:49

标签: php json api

我正试图抢夺这两种饮料的价格,并在网站上展示各自的尺寸:

"Beverage":{
    "BeverageA":[{
        "Prices":[{
            "Id":"A",
            "Size":"5.0",
            "Price":"2.0"
        },{
            "Id":"B",
            "Size":"16.0",
            "Price":"4.75",
        }],
    }],
    "BeverageB":[{
        "Prices":[{
            "Id":"A",
            "Size":"5.0",
            "Price":"2.5"
        },{
            "Id":"B",
            "Size":"16.0",
            "Price":"5.0",
        }],
    }],
}

由于两种饮料都使用“Id,Size和Price”标签,我无法在PHP中创建变量来抓取特定值,就像我通常那样:

foreach ($json_taps as $beverage) {
    $a_price = $beverage['Beverage']['Prices']['Price'];
    $b_price = $beverage['Beverage']['Prices']['Price'];

$html =
    //Display the price of beverage a
    $a_price.

    ' '.

    //Display the price of beverage b
    $b_beverage

echo $html;
}

由于这不允许我针对两种特定饮料中的哪一种,这不起作用。

我想过尝试类似的事情:

foreach ($json_taps as $beverage) {
     $id = $beverage['Beverage']['Prices']['Id'];
     $price = $beverage['Beverage']['Prices']['Price'];


$html =
    //Check for Id A
    if ($id = "A") {
        //Display price of A
        $price
    };

    //Check for Id B
    if ($id = "B") {
        //Display price of B
        $price
    };

echo $html;
}

但显然,这也行不通。

只是希望能够分别定位同一标签的两个实例以显示在页面上。在本例中,我简化了DigitalPour的JSON文件。

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

尝试按照上一个JSON结构列出饮料及其变体/价格:

$html = '';

foreach ($json_taps['Beverage'] as $beverage_name => $beverage) {
    $html .= $beverage_name.' ';

    foreach ($beverage[0]['Prices'][0] as $variant) {
        $html .= $variant['Size'].':'.$variant['Price'];
    }

}

echo $html;

如果不是您需要的话,您可以轻松访问单个饮料而不是循环使用它们,如下所示:

$beverageA = $json_taps['Beverage']['BeverageA']; // see code above inside first loop
$beverageB = $json_taps['Beverage']['BeverageB']; // etc...