对for循环中的重复元素进行分组和求和


Group and sum duplicate elements in a for loop

我有一个for循环,如下所示:

for((int) $i = 0; $i < $number_of_updates; $i++) 
{
        //query here
        $result = mysql_query($query);
        list($name) = mysql_fetch_row($result);
        $points = 1;
        //some functions to execute here... and then
        //store results in session to show on other page
        $output = $points.' times '.$name;
        $_SESSION['item'][] = $output;
}

然后我在查看页面上显示我的结果,如下所示:

foreach (array_unique($_SESSION['item']) as $output) 
{
    echo ('<p>'.$output.'</p>'); 
}

它像这样在循环外呼应我的结果:

1倍foo

1倍foo

1倍条形

1倍foo

等等。。。

现在是问题我如何总结这些结果,使它们不会重复?相反,它们是这样显示的:

3倍foo

1次条

用户array_count_values

for(/*(int) <- this is not neccessary (c++ background?) */ $i = 0; $i < $number_of_updates; $i++) 
{
    // your code
    $_SESSION['item'][] = $name;
}
foreach(array_count_values($_SESSION['item']) as $name => $times)
    echo ('<p>'.$times.' times '.$name.'</p>');

当然,直接计算数值更节省内存和时间。只有当您以某种方式需要保留元素的顺序时,才需要此版本。

为什么不直接在数组中存储总和?

for((int) $i = 0; $i < $number_of_updates; $i++) 
{
    //query here
    $result = mysql_query($query);
    list($name) = mysql_fetch_row($result);
    $points = 1;
    //some functions to execute here... and then
    //store results in session to show on other page
    $_SESSION['item'][$name] +=$points;
}

试试这个:

for((int) $i = 0; $i < $number_of_updates; $i++) 
{
        //query here
        $result = mysql_query($query);
        list($name) = mysql_fetch_row($result);
        $points = 1;
        //some functions to execute here... and then
        //store results in session to show on other page
        //$output = $points.' times '.$name;
        //$_SESSION['item'][] = $output;
        if( isset( $_SESSION['count'][$name]  )){
            $prev   = $_SESSION['count'][$name];
        }else{
            $prev   = 0;    
        }
        $_SESSION['count'][$name] = $points + $prev ;
}
print_r( $_SESSION['count'] );