2011-11-29 48 views
-2

嗨,有人可以給我一個想法如何編碼。看看陣列並從重複的值計算真或假

感謝

+4

向我們展示你的表,以及如何將數據看起來在表格中。 – BoltClock

+1

這與PHP有什麼關係? –

+0

所以你希望你的查詢返回12爲真,3爲假?還是你想讓它由用戶拆分出來,所以它對用戶1返回3而對於用戶9返回爲9? – Trott

回答

1

有使用循環的簡單(不推薦)溶液:

$resultq = mysql_query('select value, user_id from answers'); 
$answers_per_user = array(); // positive answers per user 
$totals_per_user = array(); // total answers per user 
while($result = mysql_fetch_assoc($resultq)){ 
if($result['answer']) 
$answers_per_user[$result['user_id']] += $result['answer']; // increment positive answer  counter for user 
$totals_per_user[$result['user_id']]++; 
} 

你將有一個數組每用戶,然後可以用它來計算負保持每個用戶和總的答案肯定回答答案

推薦的解決方案是使用一組由sql語句給出的所有計算信息。

$result = mysql_query('select sum(value) as positivecount, count(*) as total, user_id from answers group by user_id'); 
while($data = mysql_fetch_assoc($result)){ 
// $data will hold positivecount,total, and user_id giving you all the data you need for calculating negative answer values. 
} 
// alternatively, use a query like this for counting the answers that were 'beans': 
// select sum(if(value = "beans", 1, 0)) as answered_beans, count(*) as total, user_id from answers group by user_id 

見:http://dev.mysql.com/tech-resources/articles/wizard/page3.html

1

這個問題最優雅的解決方案實際上有兩個SQL表;每個用戶有一行(用戶ID,用戶名等)和每個投票一個,每個用戶可以有多個。

以下示例將回顯有關數據的一些信息。

<?php 
$sqlusers = mysql_query("SELECT userid FROM user_table")//This line grabs all users from the database. 
$users = mysql_fetch_array($sqlusers);//This line creates an array containing all users. 
foreach($users as $key=>$currentuser){ 
    $sqlvotes = mysql_query("SELECT userid, vote FROM vote_table WHERE userid = $currentuser[userid]"); 
    $votes = mysql_fetch_array($sqlvotes);//obtain an array of votes the current user has submitted 
    $votefrequency = array_count_values($votes)//counts the amount of trues and falses in the $votes array, and returns an array with the [true] and [false] indexes containing their respective frequency. 
    echo "user ".$userid." has voted ".$votefrequency[true]." times true and ".$votefrequency[false]." times false/n"; 
    echo "average vote:". (($votefrequency[true] - $votefrequency[false] > 0) ? "true" : "false"); 
}