2015-11-05 40 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; 
?>