PHP:填充数组时将项目限制为10

时间:2014-04-09 12:24:53

标签: php arrays limit

我使用以下方法从simpleXML字符串创建一个二维数组,到目前为止工作正常:

$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个项目,然后将所有剩余项目汇总为[其他],并将值作为剩余值的总和?

非常感谢Mike的任何帮助。

2 个答案:

答案 0 :(得分:1)

初始化计数器并在每次迭代时继续递增。在每次迭代时,检查计数器是否低于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)

不确定。要在将数组切成两半之后执行此操作,请汇总第二个块并将其附加到第一个块:

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