2014-04-09 331 views
-3

我使用下面從SimpleXML的字符串,它工作正常,到目前爲止創建一個二維數組時,限制項目10:PHP:填充陣列

$dataRaw = array(); 

foreach($objRanking->history as $history) { if($history->groupName == "currentMonth") { 
    $dataRaw[(string)$history->groupName->item] = (int)$history->groupName->groupCount; 
}} 

的數組如下所示:

Array ([item1] => 2 [item2] => 3 [item3] => 5 [item4] => 7 [item5] => 11 [item6] => 13 [item7] => 17 [item8] => 19 [item9] => 23 [item10] => 29 [item11] => 31 [item12] => 37) 

有沒有一種方法,我可以限制這種陣列內最多10個項目,然後總結所有剩餘項目爲[其他]以該值爲剩餘值的總和?

非常感謝任何幫助,邁克。

+0

如何寫這種情況下的「if」聲明? – lejlot

回答

1

Initailize計數器,並在每次迭代中不斷遞增。在每次迭代中,檢查計數器是否低於10 - 如果是這樣,像往常一樣將數據添加到數組$dataRaw。當計數器值大於10時,開始將它們添加到新陣列(此處爲$restOfTheItems)。一旦循環完成,您可以簡單地創建一個新的索引,對數組值進行求和並賦值。

$dataRaw = array(); 
$restOfTheItems = array(); 

$i = 0; 
foreach($objRanking->history as $history) { 
    if($i <= 10) { 
     if($history->groupName == "currentMonth") { 
      $dataRaw[(string)$history->groupName->item] = (int)$history->groupName->groupCount; 
     } 
    } else { 
     $restOfTheItems[] = (int)$history->groupName->groupCount; 
    } 
    $i++; 
} 

$dataRaw['Others'] = array_sum($restOfTheItems); 
+1

看到這第二個我要按新聞。你的比我的更優雅。 +1 –

+0

非常感謝 - 這真是太棒了! – Mike

1

當然。在事後做切片陣列中的兩個,總結了第二塊,並把它添加到第一:

if (count($dataRaw) > 10) { 
    $firstTen = array_slice($dataRaw, 0, 10, true); 
    $others = array_slice($dataRaw, 10, null, true); 

    $dataRaw = $firstTen; 
    $dataRaw['Others'] = array_sum($others); 
} 

當然,你可以初步處理過程中也做到這一點:

foreach($objRanking->history as $history) { 
    if($history->groupName == "currentMonth") { 
     $groupCount = (int)$history->groupName->groupCount; 
     switch(count($dataRaw)) { 
      case 11: 
       // we already have "Others", so sum the counts 
       $dataRaw['Others'] += $groupCount; 
       break; 
      case 10: 
       // we already have 10 items, so add "Others" 
       $dataRaw['Others'] = $groupCount; 
       break; 
      default: 
       // less than 10 existing items, add one 
       $dataRaw[(string)$history->groupName->item] = $groupCount; 
       break; 
     } 
    } 
} 
+0

非常感謝 - 這非常有幫助! – Mike