Php 查看数组并从重复值中计算true或false

Php 查看数组并从重复值中计算true或false,php,Php,我在SQL中有一个表,用户可以在其中多次回答(相同的用户和不同的用户)。我想计算有多少真值或假值 例如,像用户1在我的表中有5行,3次为真,2次为假,用户9有10次为真,1次为假,但我不知道用户编号 我想要我喜欢的输出 用户1-5x真1x假,用户4 1x真3x假等等,但我不知道什么用户和用户列表可以增长。这个问题最优雅的解决方案是实际拥有两个SQL表;每个用户一行(userID、username等),每个投票一行,每个用户可以有多行 下面的示例将回显有关数据的一些信息 <?php $sql

我在SQL中有一个表,用户可以在其中多次回答(相同的用户和不同的用户)。我想计算有多少真值或假值

例如,像用户1在我的表中有5行,3次为真,2次为假,用户9有10次为真,1次为假,但我不知道用户编号

我想要我喜欢的输出


用户1-5x真1x假,用户4 1x真3x假等等,但我不知道什么用户和用户列表可以增长。

这个问题最优雅的解决方案是实际拥有两个SQL表;每个用户一行(userID、username等),每个投票一行,每个用户可以有多行

下面的示例将回显有关数据的一些信息

<?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" );
}
有一种使用循环的简单(不推荐)解决方案:

$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']]++;
}
您将拥有一个数组,其中包含每个用户的肯定答案和每个用户的总答案,然后您可以使用这些答案来计算否定答案

建议的解决方案是使用GROUPBYSQL语句,该语句提供所有计算信息

$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

请参阅:

向我们展示您的表以及数据在表中的外观。这与PHP有什么关系?因此您希望查询返回12表示true,3表示false?或者,您希望它按用户划分,以便它为用户1返回3表示真,为用户9返回9表示真?那么,在您的示例中,预期的输出是
13x真,3x假
(或者类似的东西)?