2011-08-10 3 views
2

저는 PHP에서 새로 왔고 루프를 고수하게되었습니다.루프에서 값의 합계를 갖는 PHP 문제가 발생했습니다.

나는 다음과 같습니다

  • $receivers 이름이 0 또는하지를 포함하는 배열입니다.
  • $totalreceivers이라는 숫자 인 수신자의 합계를 포함하는 다른 배열입니다.
  • 0 또는 숫자를 반환하는 ID가인 테이블을 쿼리하는 함수입니다.

수신자의 각 status()을 반복하고 끝에 합계를 표시하려고합니다. 나는 그것을 얻을 수 없었다.

도움이 될 것입니다. 미리 감사드립니다. 여기

내가 뭘하려 : 코드에서

for ($i = 0; $i < $totalreceivers; $i++) 
{ 
    $status = status($receivers[$i]); 
    foreach ($totalreceivers as $value) 
     $status = status($receivers[$i]); 
    echo "the sum of receiver having status different than 0 is"; 
    echo count($status); 
} 

function status($id) 
{ 
    global $dbhost; 
    global $dbuser; 
    global $dbpass; 
    global $dbname; 
    global $d1; 

    $q2 = mysql_query("select * from user where id ='$id' AND subscription_end_date IS NULL", $d1); 

    while($row2 = mysql_fetch_array($q2)) 
     $rowservice = $row2['value']; 
    return $rowservice; 
} 
+0

당신은 좋은 방법으로 문제를 해결하지 않았다. 질문을 귀하의 문제를 해결할 수 있도록 포맷하십시오. –

+0

* 하나의 * 쿼리로 MySQL 내에서 합계를 계산할 수 있습니다. Ref : http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_sum – hakre

답변

0

MySQL이 더 많은 작업을 수행하도록하면이 작업을 단순화 할 수 있습니다.

배열에 $receivers이 있는데 여기에는 아마도 수신자의 수신자를위한 ID가 포함되어있을 것입니다. (나는 수신기와 가입자를 교환하여 사용할 수있다.)

status() 함수는 subscription_end_date이 null 인 각 수신기에 대해 value을 데이터베이스에서 검색한다. 변수 $rowservice을 통해 마지막 결과 만 반환하기 때문에 구독자 당 하나의 행만 있다고 가정합니다.

value이 0이 아닌 수신기 개수를 원하거나 0이 아닌 값의 합계를 원하면 코드에서 명확하지 않습니다. 그러면 문제는 다음과 같습니다.

  • 얼마나 많은 가입자가 0이 아닌 값을 갖고 있는지 알고 싶습니까?또는
  • 0이 아닌 값을 가진 구독자의 모든 값의 합을 알고 싶습니까?

은 다행스럽게도이 두 쉽게 찾을 수 있습니다

얼마나 많은 수신기가 아닌 0 값이?

$allreceivers = implode(',', $receivers); 
$query = "SELECT COUNT(id) AS total_receivers 
    FROM user 
    WHERE subscription_end_date IS NULL 
    AND value != 0 
    AND id IN ($allreceivers);"; 
$result = mysql_query($query, $d1); 
$row = mysql_fetch_array($result); 
$total_receivers = $row['total_receivers']; 

echo "The number of receivers having status (value) other than 0 is $total_receivers"; 

모든 수신기 값의 합은 무엇인가?

$allreceivers = implode(',', $receivers); 
$query = "SELECT SUM(value) AS receiver_value_sum 
    FROM user 
    WHERE subscription_end_date IS NULL 
    AND id IN ($allreceivers);"; 
$result = mysql_query($query, $d1); 
$row = mysql_fetch_array($result); 
$receiver_value_sum = $row['receiver_value_sum']; 

echo "The sum of receiver values is $receiver_value_sum"; 
+0

JYelton, 당신은 스타입니다. 멋지게 잘되었습니다. 감사합니다. – user888300

+1

@ user888300을 환영합니다. [vote] (http://stackoverflow.com/privileges/vote-up)를 잊지 마십시오. :) – JYelton

1

몇 가지 정말 이해가되지 않습니다. 먼저, 을 두 번 반복하여 $totalreceivers을 두 번 반복하면 하나의 루프가 다른 루프에 중첩됩니다. 나는 그것이 당신이 원하는 것을 의심하므로 그들 중 하나를 제거해야합니다. 첫 번째 루프의 표현이 좋지 않습니다. 첫 번째 for 루프에서 $totalreceivers을 반복하려면 테스트 표현식을 배열 자체가 아니라 배열 자체의 요소 수 (count()를 사용할 수 있음)로 설정해야합니다. for ($i = 0; $i < count($totalreceivers); $i++).

두 번째로 루프에서 status()을 호출 할 때마다 $status의 값을 재설정합니다. 추가하려면 += 연산자를 사용하십시오. $status += status($receivers[$i]);

세 번째로 status() 함수에서 $rowservice으로 동일하게 작업하고 있습니다. 루프를 반복 할 때마다 while 루프가 다시 설정됩니다. 한 번 설정하거나 요약하십시오.

0

언뜻보기에 각 반복마다 "$ status"를 덮어 쓰는 것 같습니다. 루프가 시작되기 전에 $ status를 빈 배열로 설정 한 다음 각 반복마다 추가하십시오. 예를 들면 다음과 같습니다.

$status = array(); 
    foreach ($totalreceivers as $value) 
    { 
    $status[] = status($receivers[$i]); 
    } 
    echo count($status); 
0

나는 아래 코드 몇 가지 가능한 문제를 간략하게 설명하려고합니다 :

for ($i = 0; $i < $totalreceivers; $i++) { //This open bracket has no end bracket 
/*I assume total receivers is the number of receivers; if that is the case, it shouldn't be an array, but merely a value.*/ 
      $status = status($receivers[$i]); 
/*I think you should define the status function before you call it; also, if you are just calling the status function for each value of $receivers, why don't you just do a foreach($receivers as $value) loop, like you did below with $totalreceivers. */ 
     foreach ($totalreceivers as $value) 
/*I'm not sure what $totalreceivers is. You said its an array containing total number of receivers; again, I would think this would be a single value, and not an array*/ 
     { 
     $status = status($receivers[$i]); 
/*looks like you're calling the status function again*/ 
     } 
      echo "the sum of receiver having status different thant 0 is"; echo count($status); 
/* $status at this point would count the value from row2 for the last value in $receivers, and not a count of array values. Perhaps you could do $status[] = status($receivers[$i]), and then count($status) to save each value to an array, then count the elements. */ 

function status($id){ 
global $dbhost; 
global $dbuser; 
global $dbpass; 
global $dbname; 
/* The values above aren't used in the function; you may want to connect to the database outside of the function, before the foreach loop. */ 
global $d1 ; 

$q2 = mysql_query("select * from user where id ='$id' AND subscription_end_date IS NULL",$d1); 
while($row2 = mysql_fetch_array($q2)){ 
$rowservice = $row2['value']; 
} 
return $rowservice; 
} 
/*the rest looks good*/ 
+0

팁 덕분에, 도와 줬어. – user888300

관련 문제