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

时间:2011-11-29 00:30:07

标签: php

嗨,有人可以告诉我如何编写代码。

感谢

2 个答案:

答案 0 :(得分:1)

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

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

<?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" );
}

答案 1 :(得分: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