2013-03-25 35 views
3

我有我的数据库中的字段包含字符串像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”而不是总和。

+6

使用爆炸拆分了绳子,然后计算的总和:'array_sum(爆炸( ';' ,$ points));' – h2ooooooo 2013-03-25 09:03:42

+2

这是因为你从来没有**计算**它... – Passerby 2013-03-25 09:03:55

回答

2
$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); 
0

最简单的方法是explode的字符串。

然后,您可以使用foreach迭代遍历结果数组并计算它们。

$points = "21;48;33;22;31"; 
$points = explode(";", $points); 
$calc = 0; 

forearch($points as $point) { 
    $calc += $point; 
} 

或者您可以使用array_sum

$points = "21;48;33;22;31"; 
$points = explode(";", $points); 
$calc = array_sum($points); 

类似的东西。也许有一些简短的方法。

8
$points = "21;48;33;22;31"; 
$points = explode(';',$points); 
$points = array_sum($points); 
echo $points; 
0
$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 
0

爆发,然后和循环...

<?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; 
    ?> 
0
<?php 
eval('$sum = ' . str_replace(';','+','21;48;33;22;31').';'); 
echo $sum;