2012-06-16 34 views
0

我具有由外包數據:如何填充此PHP數組?

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
類別:博客/保健/護膚

標題:Business 2
類別:博客/業務/本地

標題:生2
類別:博客/保健/護膚

的問題是如何顯示輸出爲以下幾點:

2上週熱門商業用品

標題:Business 1
類別:商業營業

標題:企業2
分類:商業

上週2流行健康文章

標題:生1
範疇:健康

標題:生2
分類:健康

幫助將不勝感激!謝謝。

+1

不知道如果我理解正確的話......只需通過數組迭代,檢查是否'title'包含'Business'並顯示它? – Pateman

+0

嗨,感謝您的回答我是PHP新手,如果您舉個例子,那將會很棒。 :-D – Rifki

回答

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; 
+0

嗨,是的,我也把這段代碼,但我不知道可能吃編輯 – Rifki

+0

嘿,請看看我已經做了一個更改的代碼 – Rifki

+0

請看我的更新,對不起,很難格式化在我的手機上打字時 – Andrew

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

該類別被視爲僅** **業務 – hjpotter92

+0

對。糾正。 – Pateman

+0

問題是標題並不總是包含「商業」。 – Rifki