对分隔字符串数组中的子字符串值求和

问题描述 投票:0回答:3

我有两个cookie,它们的值是这样的:

foreach ($_COOKIE as $key => $val) {
    $piece = explode(",", $val);
    $t_cost = array($piece[3]);
    print_r($t_cost); //It prints Array ( [0] => 11 ) Array ( [0] => 11 )
    echo $total_cost = array_sum($t_cost);
}

但它只打印一个值。如何将这两个值相加来求和?

php arrays sum substring delimited
3个回答
2
投票

我认为你不需要 array_sum,只需使用 += 运算符即可节省一点内存

$t_cost = 0;
foreach($_COOKIE as $key=>$val) {
    $piece = explode(",", $val);
    $t_cost += $piece[3];
}
echo $t_cost;

1
投票
$total = 0;
foreach($_COOKIE as $key=>$val) {
      $piece = explode(",", $val);
      $t_cost = trim(str_replace('$', '', array($piece[3]));
      $total += (float)$t_cost;
      echo "The total cost: $".$total;
}

1
投票

实际上不需要

array_sum

// the array where all piece[3] values are stored
$t_cost = array();

// loop through array
// just foreach($_COOKIE as $val) is enough
foreach($_COOKIE as $key=>$val) {

    // split by comma
    $piece = explode(",", $val);

    // add to array
    $t_cost[] = $piece[3];

}
// sum up  
$total_cost = array_sum($t_cost);   

或者只是

$total = 0;
foreach($_COOKIE as $key=>$val) {
        $piece = explode(",", $val);  
        $total += $piece[3];
}
echo $total;
© www.soinside.com 2019 - 2024. All rights reserved.