2011-11-29 2 views
-2

안녕하세요. 누군가이 코드를 작성하는 방법을 알려줄 수 있습니다.어레이를보고 중복 값에서 참 또는 거짓을 계산하십시오.

감사

+4

우리에게 테이블 방법과 데이터가 테이블에 보일 것을 표시합니다. – BoltClock

+1

이것은 PHP와 어떤 관련이 있습니까 ?? –

+0

그렇다면 쿼리가 true를 12로, false를 3으로 반환하도록 하시겠습니까? 아니면 그것은 사용자에 의해 나뉘어지기를 원합니? 그래서 사용자 1에게는 3을, 사용자 9에 대해서는 9를 반환합니다. – Trott

답변

1

대답

권장되는 솔루션은 모든 계산 된 정보를 제공하는 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, 사용자 이름 등)이고 하나는 각 투표에 대해 하나의 사용자 당 여러 명이 될 수 있습니다.

다음 예는 데이터에 대한 일부 정보를 표시합니다. 당신이 배열하면 다음 부정적인 계산하는 데 사용할 수있는 사용자별로 사용자와 전체 답변 당 긍정적 인 답변을 잡고 것이다

$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']]++; 
} 

: 루프를 사용하여 간단한 (권장하지 않음) 솔루션이

<?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"); 
} 
관련 문제