簡體   English   中英

如何填充此PHP數組?

[英]How to populate this PHP array?

我有來自的外包數據:

http://example.com/data/news.json

這是解碼后的示例結果:

Array
(
    [popular] => Array
        (
            [last_week] => Array
                (
                    [0] => Array
                        (
                           [title] => Business 1
                            [category] => blog/business/local
                        )
                    [1] => Array
                        (
                        [title] => Health 1
                        [category] => blog/health/skincare
                    )
                [2] => Array
                    (
                        [title] => Business 2
                        [category] => blog/business/local
                    )
                [3] => Array
                    (
                        [title] => Health 2
                        [category] => blog/health/skincare
                    )
            )
    )

)

我正在使用以下方法來顯示它:

$url = 'http://example.com/data/news.json';
$json = file_get_contents($url);
if(!empty($json)) {
$json_data = json_decode($json, true);
$popular_last_week = $json_data['popular']['last_week'];
$count = count($popular_last_week);
$result .= $count.' last week popular article' . "\n";
for ($i = 0;  $i <$count; $i++) {
$result .= 'Title : '.$popular_last_week[$i]['title'] . "\n";
$result .= 'Category : '.$popular_last_week[$i]['category'] . "\n\n";
}
echo $result;
}

輸出數據為:


類別:博客/企業/本地




問題是如何顯示以下輸出:





幫助將不勝感激! 謝謝。

$url = 'http://example.com/data/news.json';
$json = file_get_contents($url);
if(!empty($json)) {
    $json_data = json_decode($json, true);
    $popular_last_week = $json_data['popular']['last_week'];

    //  This loop will group all entries by category.
    $categories = array();
    foreach ($popular_last_week as $item) {
        $categories[$item['category']][] = $item['title'];
    }

    //  This loop will echo the titles grouped by categories.
    foreach ($categories as $category => $titles) {
        $result = count($titles) . ' popular in "' . $category . '"' . "\n";
        foreach ($titles as $title) {
            $result .= 'Title: ' . $title . "\n";
        }
        echo $result;
    }
}

您是說只想顯示2個項目嗎? 您需要使用for循環。

for ($i = 0;  $i < 2; $i++) {
    # display for $i
}

更新:

嗯,我想我明白了。 您應該使用foreach循環並循環兩次:

$categoryItems = array();
foreach ($popular_last_week as $item) {
    $categoryItems[$item['category']][] = $item['title'];
}
foreach ($categoryItems as $category => $items) {
    $result .= count($items) . ' popular in category ' . $category;
    foreach ($items as $item){
        $result .= 'Title: ' . $item['title'] . "\n";
    }
}
echo $result;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM