我需要将结果集值加上" |"在循环内部例如。一组值10 | 2,6 | 2,8 | 1应该导致24 | 5。
这是我的代码:
<?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
现在结果,
"Pending":"16|9"
"Pending":"11|3"
"Pending":"6|2"
我的预期结果,
"Pending":"33|14"
答案 0 :(得分:1)
这就是你的目标,我认为,你首先创建一个包含2个值的数组,在每次迭代中通过循环向它们添加新值,最后你可以将它再次内爆成一个字符串
// 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);
您想要的字符串值将位于$stringTotalpending
答案 1 :(得分:0)
首先,我们需要从$row["Pending"]
爆炸值。
$arr = explode("|", $row["Pending"]);
现在使用循环添加这两个数字:
$temp = 0;
for($i = 0; $i < count($arr); $i++){
$temp += (int) $arr[$i];
}
现在$temp
将包含结果。
就这么简单。
另外,作为旁注,您的代码容易受到SQL注入攻击。
答案 2 :(得分:0)
用'|'评估相同的字符串怎么样?替换为'+'?
eval('$result = ' . str_replace('|', '+', preg_replace('/[^0-9|]/', '', $row["Pending"])) . ';');
echo "$result\n";
注意preg_replace()来清理输入。如果输入已经消毒,则可以避免