2016-04-01 25 views
-2

ile ayrılmış değerleri ayırın "|" ile ayrılmış sonuç kümesi değerlerini toplamalıyım döngü içinde örneğin. 10 | 2, 6 | 2, 8 | 1 değerleri kümesi 24 | 5 ile sonuçlanmalıdır. Biz $row["Pending"] değerleri patlayabilir gerekir Yani Önceliklephp toplam değerleri

<?php 
$fromdate="2016-03-31"; 
$todate="2016-03-31"; 
$TAG="1"; 
$con = mysqli_connect("XXXXX","XX","XXX","XXX"); 
$query = mysqli_query($con, "CALL sp_Android_Online_Dashboard('$fromdate', '$todate','$TAG')") or die("Query fail: " . mysqli_error()); 
$Totfiles = 0; 
$file_minutes = 0; 
$Tot_minutes=0; 
$Pending=0; 
while(($row = mysqli_fetch_array($query))) 
{ 
    $Totfiles +=$row["Totfiles"]; 
    $file_minutes +=$row["file_minutes"]; 
    $Pending =str_replace(array("/"),"|",$row["Pending"]); //need to sum all the values separated by "|" 
    $Tot_minutes +=$row["Tot_minutes"]; 
} 
$response["Details"]['Totfiles'] = $Totfiles; 
$response["Details"]['file_minutes'] = $file_minutes; 
$response["Details"]['Pending'] = $Pending; 
$response["Details"]['Tot_minutes'] = $Tot_minutes; 
echo json_encode($response);  
?> 

$row["Pending"] contains the values which are to be summed 

sonuç artık alıyorum,

"Pending":"16|9" 
"Pending":"11|3" 
"Pending":"6|2" 

benim beklenen sonuç,

"Pending":"33|14" 

cevap

1

Bu bence, sen onlara ve sonunda yeni değerler eklemek döngü içinde her tekrarında, ilk 2 değerlerini içeren bir dizi yapmak tekrar bir dizeye

bunu çöker olabilir sen hedefliyoruz budur
// Start with an array containing 0 twice 
$Totalpending = [0,0]; 
while(($row = mysqli_fetch_array($query))) 
{ 
    // On each loop we add the left value to the first value in the array and the right value to the second value in the array 
    $tmp = explode("|", $row['Pending']); 
    $Totalpending[0] += $tmp[0]; 
    $Totalpending[1] += $tmp[1]; 

    $Totfiles +=$row["Totfiles"]; 
    $file_minutes +=$row["file_minutes"]; 
    $Pending =str_replace(array("/"),"|",$row["Pending"]); //need to sum all the values separated by "|" 
    $Tot_minutes +=$row["Tot_minutes"]; 
} 
// if you want to format the values in the same way again, although an array is much easier to handle, but it's up to you. 
$stringTotalpending = implode('|',$Totalpending); 

o zaman ne ile aynı dizeyi evaling hakkında $stringTotalpending

0

: Burada

benim kodudur .

$arr = explode("|", $row["Pending"]); 

Şimdi bu iki sayıyı eklemek için bir döngü kullanın:

$temp = 0; 
for($i = 0; $i < count($arr); $i++){ 
    $temp += (int) $arr[$i]; 
} 

Şimdi $temp sonucu içerecektir.

Bu kadar basit. Ayrıca, bir yan not olarak, kodunuz SQL-Injection saldırılarına karşı savunmasızdır.

0

olacak istediğiniz dize değeri '|' '+' ile değiştirildi mi?

eval('$result = ' . str_replace('|', '+', preg_replace('/[^0-9|]/', '', $row["Pending"])) . ';'); 
echo "$result\n"; 

Girişi önlemek için preg_replace() öğesini not edin. Giriş zaten

dezenfekte edilirse önlenebilir
İlgili konular