1

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

1 次

1倍吧

1 次

ETC...

现在的问题。我如何总结这些结果,以免它们重复?相反,它们显示如下:

3 次

1倍吧

4

3 回答 3

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

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

于 2013-09-04T15:15:40.610 回答
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;
}
于 2013-09-04T15:16:15.903 回答
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'] );
于 2013-09-04T15:19:31.000 回答