2015-11-05 47 views
1

运行值我有这个在PHP:在一个字符串

$arreglo = array('128 gigas', '250 gigas', '220 gigas'); 
foreach ($arreglo as $key => $value) { 

} 

是否有可能在字符串中运行这些价值?像128 + 250 + 220,使用foreach? 预先感谢您。

回答

0

如果字符串总是遵循该格式,那么是的。你可能会爆炸的字符串到数组:

$a = explode(' ', $string); // Now $a[0] contains the number 

因此,对于您的代码:

$arreglo = array('128 gigas', '250 gigas', '220 gigas'); 
$total = 0; 
foreach ($arreglo as $value) { // $key not necessary in this case 
    $a = explode(' ', $value); 
    $total += $a[0]; // PHP will take care of the type conversion 
} 

或者,如果你感觉创意:

$func = function($s) { 
    $a = explode(' ', $s); 
    return $a[0]; 
}; 

$arreglo = array('128 gigas', '250 gigas', '220 gigas'); 
$numbers = array_map($func, $arreglo); 
$total = array_sum($numbers); 
0

使用下面的代码:

$arreglo = array('128 gigas', '250 gigas', '220 gigas'); 
$arr = array(); 
$i = 0; 
foreach ($arreglo as $key => $value) 
{ 
    $expVal = explode(" ",$vaulue); 
    $arr[$i] = $expVal[0]; //this array contains all your numbers 128, 250 etc 
} 
$sum = 0; 
foreach($arr[$i] as $num) 
{ 
    $sum = $sum+$num 
} 
echo $sum; // your final sum result is here 
0

你可以用基本的PHP功能:

explode()

implode()

str_replace()

工作例如:

<?php 
$arreglo = array('128 gigas', '250 gigas', '220 gigas'); 
$str = implode(',', $arreglo); 
$str = str_replace(' gigas', '', $str); 
$n = explode(',', $str); 
$count = array_sum($n); 
echo $count; // Outouts 598 
?> 
0

如果数字和字母之间的空间总是有的,你可以做到这一点

$arreglo = array('128 gigas', '250 gigas', '220 gigas'); 
$total = 0; 
foreach ($arreglo as $value) { 
    $total += strstr($value, " ", true); 
} 
echo "Total : $total"; // int(598) 
0

尝试......

<?php 
    $total=0; 
    $arreglo = array('128 gigas', '250 gigas', '220 gigas'); 
foreach ($arreglo as $key => $value) { 
$total +=intval(preg_replace('/[^0-9]+/', '', $value), 10); 
} 
echo $total; 
    ?> 

演示:https://eval.in/463363

0

您可以用做array_map()str_replace()array_sum()

工作实例:

<?php 
$data = array('128 gigas', '250 gigas', '220 gigas'); 
$data = array_map(function($value) { return str_replace(' gigas', '', $value); }, $data); 
echo array_sum($data); 
?> 

See it live here

说明:

1)你有字符串值的数组。这些值也包含数字。

2)您需要对所有数字进行求和。

3)使用array_map()可以使用str_replace()替换字符串中的所有非数字字符。

4)现在,使用array_sum()来总和。

0

如果你想内嵌代码

echo array_sum(str_replace(" gigas","",$arreglo)); 
0

您可以简单地使用floatval()PHP函数来得到一个字符串的浮点值。希望这可以帮助。

$arreglo = array('128 gigas', '250 gigas', '220 gigas'); 

$sum=0; 
foreach($arreglo as $value){ 
    $sum += floatval($value); 
} 

print $sum; 
0

试试这个

<?php 
$arreglo = array('128 gigas', '250 gigas', '220 gigas'); 
$sum=0; 
foreach ($arreglo as $key => $value) { 
$sum+=(int)$value; 
} 
echo $sum; 
?>