字符串作为计算在php
问题描述:
我有我的数据库中的字段包含字符串像21;48;33;22;31
。然后我想将其转换为数学计算21+48+33+22+31
。字符串作为计算在php
$points = "21;48;33;22;31";
$points = str_replace(";","+",$points);
$points = preg_replace('/[^0-9\+\-\*\/\s]+/', '', $points);
echo $points;
但是,这根本不起作用。我有相同的字符串“21 + 48 + 33 + 22 + 31”而不是总和。
答
$points = "21;48;33;22;31";
$arr = explode(";", $points);
$points = 0;
foreach($arr as $key => $rows){
$points += $rows[$key];
}
echo $points;
试试上面的代码,它会给你正确的结果。
,或者你也可以尝试一下:
$points = "21;48;33;22;31";
$arr = explode(";", $points);
echo $points = array_sum($arr);
答
$points = "21;48;33;22;31";
$points = explode(';',$points);
$points = array_sum($points);
echo $points;
答
$string = "21;48;33;22;31";
$string = explode(";" , "21;48;33;22;31");
$point = 0;
foreach($string as $num)
{ // by using (int) you can convert string to int.
$point = (int)$num + $point;
}
print($point);
// output
155
答
爆发,然后和循环...
<?php
$total = 0; // for getting the total
$points = "21;48;33;22;31";
$points = explode(';',$points);
for($i=0;$i<count($points);$i++){
$total+= $points[$i];
}
echo $total;
?>
答
<?php
eval('$sum = ' . str_replace(';','+','21;48;33;22;31').';');
echo $sum;
使用爆炸拆分了绳子,然后计算的总和:'array_sum(爆炸( ';' ,$ points));' – h2ooooooo 2013-03-25 09:03:42
这是因为你从来没有**计算**它... – Passerby 2013-03-25 09:03:55