PHP foreach迭代JSON数据输出

时间:2015-12-23 02:08:51

标签: php arrays json

好的,所以我正在尝试获取一些JSON数据并将其输出到PHP页面中。到目前为止,我的PHP代码看起来像这样:

<?php                                                                    
$string = 
    $string = 
    file_get_contents("https://service.digitalpour.com/BeerDashboard/api/v2/MenuItems/53716a8dfb890c0d68677264/1/Tap?apiKey=53926cc7fb890c0528735cde");

    $json_taps = json_decode($string, true);  


$t=1; 
echo '<div id="taplist-container">'; 

foreach ($json_taps as $beverage) { 

        $item_name = $beverage['MenuItemDisplayDetail']['DisplayName'];
        $producer_name = $beverage['MenuItemProductDetail']['FullProducerList'];
        $beverage_name = $beverage['MenuItemProductDetail']['BeverageNameWithVintage'];
        $beverage_style = $beverage['MenuItemProductDetail']['FullStyleName'];
        $beverage_color = $beverage['MenuItemProductDetail']['Beverage']['StyleColor'];
        $year = $beverage['MenuItemProductDetail']['Year'];
        $beverage_abv = $beverage['MenuItemProductDetail']['Beverage']['Abv'];
        $beverage_ibu = $beverage['MenuItemProductDetail']['Beverage']['Ibu'];
        $beverage_type = $beverage['MenuItemProductDetail']['BeverageType'];
        $beer_advocate = $beverage['MenuItemProductDetail']['Beverage']['BeerAdvocateUrl'];
        $rate_beer = $beverage['MenuItemProductDetail']['Beverage']['RateBeerUrl'];

        $price = $beverage['MenuItemProductDetail']['Prices'][0]['Price'];
        $size = $beverage['MenuItemProductDetail']['Prices'][0]['DisplayName'];

        $producer_location = "";
        $producer_url = "";
        switch($beverage_type) {
            case "Beer":
                $producer_location = $beverage['MenuItemProductDetail']['Beverage']['Brewery']['Location'];
                $producer_url = $beverage['MenuItemProductDetail']['Beverage']['Brewery']['BreweryUrl'];
                break;
            case "Cider":
                $producer_location = $beverage['MenuItemProductDetail']['Beverage']['Cidery']['Location'];
                $producer_url = $beverage['MenuItemProductDetail']['Beverage']['Cidery']['CideryUrl'];
                break;
            case "Mead":
                $producer_location = $beverage['MenuItemProductDetail']['Beverage']['Meadery']['Location'];
                $producer_url = $beverage['MenuItemProductDetail']['Beverage']['Meadery']['MeaderyUrl'];
                break;
            case "Wine":
                $producer_location = $beverage['MenuItemProductDetail']['Beverage']['Winery']['Location'];
                $producer_url = $beverage['MenuItemProductDetail']['Beverage']['Winery']['WineryUrl'];
                break;
            case "Kombucha":
                $producer_location = $beverage['MenuItemProductDetail']['Beverage']['KombuchaMaker']['Location'];
                $producer_url = $beverage['MenuItemProductDetail']['Beverage']['KombuchaMaker']['Url'];
                break;
            case "Soft Drink":
                $producer_location = $beverage['MenuItemProductDetail']['Beverage']['SoftDrinkMaker']['Location'];
                $producer_url = $beverage['MenuItemProductDetail']['Beverage']['SoftDrinkMaker']['Url'];
                break;
        }
        $date_put_on = $beverage['DatePutOn']; 
        $bottle_size = $beverage['MenuItemProductDetail']['Prices'][0]['Size'];   
        $bottle_price = $beverage['MenuItemProductDetail']['Prices'][0]['Price'];
        $beverage_ps = $beverage['MenuItemProductDetail']['Prices'][0]['DisplayName']; 
        $in_bottles = $beverage['MenuItemProductDetail']['AvailableInBottles'];
        $keg_size = $beverage['MenuItemProductDetail']['KegSize'];
        $oz_remaining = $beverage['MenuItemProductDetail']['EstimatedOzLeft'];
        $scale = 1.0; //


    //calculating percentage of keg remaining
    // Get Percentage out of 100
    if ( !empty($keg_size) ) { $percent = $oz_remaining  / $keg_size; } 
    else { $percent = 0; }

    // Limit to 100 percent (if more than the max is allowed)
    if ( $percent > 1 ) { $percent = 1; }     
    if ( $percent < 0 ) { $percent = .005; }     
    $percent_remaining = number_format($percent*100, 0);
    if ( $percent_remaining < 1 ) {$percent_remaining = "< 1";}

    //determine percent Left color
    //                  |-----------Red ---------------------------|   |-------Green--------------------| |Blue|
    $percent_left_color = (max(0,min(255,511 * (1-$percent))) * 65536) + (max(0,min(255,511 * $percent)) * 256) + 40;

    $html =  
        '<div class="keg-info">'.
        '<div class="boxfielddata" title="'.$percent_remaining.'% remaining" >'. 

        '<div class="brewery">'.(!empty($producer_url) ? '<a href="http://'.$producer_url.'" target="_blank">' : '</a>').$producer_name.'</a> '.'</div>'.
        '<div class="beverage-name">'.$beverage_name.'</div>'.
        '<div class="beverage-type">'.$beverage_style.'</div>'.
        '<div class="abv">ABV: '.$beverage_abv.'% | IBU: '.$beverage_ibu.'</div>'.
        '<div class="reviews">
            <a href="'.$beer_advocate.'" target="_blank" rel="nofollow">BeerAdvocate.com</a> | <a href="'.$rate_beer.'" target="_blank" rel="nofollow">RateBeer.com</a>
        </div>'.
        '<div class="beverage-type">'.$displaySize.'</div>'.
        '<span>'.($beverage_ps == '12oz' ? $beverage_ps : '').'</span>'.
        '<span style="position:relative;">'.($in_bottles == TRUE 
? '<a href="/dev/?page_id=7&so=brewery">Available in bottles!</a>' : 
'').'</span>'.    
//PERCENTAGE AND COLOR
        '<div class="percent-remaining" style="width:'.round(100 * $scale).'px;">'.
        '<div style="width:'.round(max($percent*100,5) * $scale).'px; height: 20px; background-color: #'.substr("000000".dechex($percent_left_color),-6).';"></div>'.
        '</div>'.
        '<div class="percent-number">'.$percent_remaining.'%</div>'.
        '</div></div>'.  

        ($t == $countnumrows ? '</div><div id="shim"></div><div id="datafieldcontainer">' : '');    

echo $html;
$t++;     
}

?>

此产品的效果非常好,但饮料有多种尺寸和价格,具体取决于尺寸。例如,您可以使用上面代码中的链接访问我的JSON Feed,但这是其中一种饮料的片段,它的大小/价格不同:

Year: 2015,
Attributes: [ ],
HasVintage: false,
    Prices: [
    {
    Size: 5,
    Price: 2,
    DisplayName: "Taster",
    DisplaySize: 5.5,
    UPCCode: null,
    Glassware: "Nonic (Small)",
    DisplayOnMenu: false
    },
    {
    Size: 9.5,
    Price: 4,
    DisplayName: "10oz",
    DisplaySize: 10,
    UPCCode: null,
    Glassware: "Nonic (Small)",
    DisplayOnMenu: true
    },
    {
    Size: 15.5,
    Price: 6,
    DisplayName: "16oz",
    DisplaySize: 16,
    UPCCode: null,
    Glassware: "Nonic",
    DisplayOnMenu: true
    },
    {
    Size: 35.2,
    Price: 11,
    DisplayName: "32oz",
    DisplaySize: 32,
    UPCCode: null,
    Glassware: "Growler",
    DisplayOnMenu: false
    },
    {
    Size: 70.4,
    Price: 18,
    DisplayName: "64oz",
    DisplaySize: 64,
    UPCCode: null,
    Glassware: "Growler",
    DisplayOnMenu: false
    }
    ],
EventPrices: null,
EventPricesActive: false,
EventId: null,
EventName: null,
DateAdded: "2015-12-09T18:57:30.517Z",
ProductFinished: false,
BeverageNameWithVintage: "Eliot IPA",
FullBeverageName: "Ex Novo Eliot IPA",
FullProducerList: "Ex Novo",
FullStyleName: "IPA - Hops (Galaxy, Simcoe, Centennial & Southern Cross)",
EventItem: false,
ReplaceableItem: false
},
Active: true,
DatePutOn: "2015-12-15T00:50:51.709Z",
DatePulledOff: null
},

所以我想要做的是弄清楚我可以输出不同大小和价格与我输出的其余数据(参见上面的PHP代码)并显示各种可用的尺寸和价格每种饮料都是这样的:

品尝者:2美元 10oz:4美元 16oz:6美元 32oz:11美元 64盎司:18美元

等等......

我想出了使其在下面工作的代码:

foreach($beverage['MenuItemProductDetail']['Prices'] as $price) {
    echo '<p>'.$price['DisplayName'].': $'.$price['Price'].'</p>';
}

但我不确定如何将该代码与下面的html输出内联:

    $percent_left_color = (max(0,min(255,511 * (1-$percent))) * 65536) + (max(0,min(255,511 * $percent)) * 256) + 40;

    $html =  
        '<div class="keg-info">'.
        '<div class="boxfielddata" title="'.$percent_remaining.'% remaining" >'. 

        '<div class="brewery">'.(!empty($producer_url) ? '<a href="http://'.$producer_url.'" target="_blank">' : '</a>').$producer_name.'</a> '.'</div>'.
        '<div class="beverage-name">'.$beverage_name.'</div>'.
        '<div class="beverage-type">'.$beverage_style.'</div>'.
        '<div class="abv">ABV: '.$beverage_abv.'% | IBU: '.$beverage_ibu.'</div>'.
        '<div class="reviews">
            <a href="'.$beer_advocate.'" target="_blank" rel="nofollow">BeerAdvocate.com</a> | <a href="'.$rate_beer.'" target="_blank" rel="nofollow">RateBeer.com</a>
        </div>'.
        '<div class="beverage-type">'.$displaySize.'</div>'.
        '<span>'.($beverage_ps == '12oz' ? $beverage_ps : '').'</span>'.
        '<span style="position:relative;">'.($in_bottles == TRUE 
? '<a href="/dev/?page_id=7&so=brewery">Available in bottles!</a>' : 
'').'</span>'.    
//PERCENTAGE AND COLOR
        '<div class="percent-remaining" style="width:'.round(100 * $scale).'px;">'.
        '<div style="width:'.round(max($percent*100,5) * $scale).'px; height: 20px; background-color: #'.substr("000000".dechex($percent_left_color),-6).';"></div>'.
        '</div>'.
        '<div class="percent-number">'.$percent_remaining.'%</div>'.
        '</div></div>'.  

        ($t == $countnumrows ? '</div><div id="shim"></div><div id="datafieldcontainer">' : '');    

echo $html;
$t++;     
}

?>

1 个答案:

答案 0 :(得分:1)

尝试使用此尺寸。您可以随意使用标记,并根据自己的喜好进行重构:

新行是:

第59-64行:

function txtExpChange(txt)
{
    if (!isSave)
    {
        // Do stuff
    }

    return isSave;
}

和第111-112行:

$bottlePrices = $beverage['MenuItemProductDetail']['Prices'];

$pricesSizesHtml = "";
foreach($bottlePrices as $prices){
    $pricesSizesHtml .= $prices['DisplayName'] . ": $" . $prices['Price'] . "<br>";
}

示例输出:

//Prices and Sizes
 '<div class="prices-sizes">'.$pricesSizesHtml.'</div>'.

代码:

Ex Novo
Eliot IPA
IPA - Hops (Galaxy, Simcoe, Centennial & Southern Cross)
ABV: 6.6% | IBU: 65
BeerAdvocate.com | RateBeer.com
70%
Taster: $2
10oz: $4
16oz: $6
32oz: $11
64oz: $18