如何填充这个PHP数组?

时间:2012-06-16 06:42:49

标签: php arrays

我有来自的外包数据:

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
类别:健康

帮助将不胜感激!谢谢。

2 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分: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;