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回フー

等...

今質問です。重複しないようにこれらの結果を合計するにはどうすればよいですか? 代わりに、次のように表示されます。

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
        //$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 に答える
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 に答える