0

我有一个外包数据:

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;
}

输出数据为:

4 上周热门文章

标题:业务 1
类别:博客/业务/本地

标题:健康 1
类别:博客/健康/护肤

标题:业务 2
类别:博客/业务/本地

标题:健康 2
类别:博客/健康/护肤

问题是如何显示输出如下:

2 上周热门商业文章

标题:业务 1
类别:业务

标题:业务 2
类别:业务

2 上周热门健康文章

标题:健康 1
类别:健康

标题:健康 2
类别:健康

帮助将不胜感激!谢谢你。

4

2 回答 2

3
$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;
    }
}
于 2012-06-16T06:55:14.303 回答
0

你的意思是你只想显示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;
于 2012-06-16T06:54:34.670 回答