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

时间:2013-09-04 15:12:04

标签: php loops

我有一个像这样的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次酒吧

3 个答案:

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

当然直接计算值是更多的内存和时间效率。如果您以某种方式需要保留元素的顺序,则只需要此版本。

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

试试这个:

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'] );