dongliantong3229
2016-06-08 14:49
浏览 13
已采纳

如何在PHP中用DB计算字符串中的数字

I echo some numbers from the database and show only those numbers with a foreach. I now want to calculate the total of these numbers.

$test = str_replace('\\', '', $orderDetails['jsonData']);
$bonbonOrders = unserialize($test);

foreach($bonbonOrders as $bonbonOrder){
    foreach($bonbonOrder as $bonbons){
        echo $bonbons['gewicht'];
    }
}

I tried several things but I really don't know how I can calculate them.

the output for a example can be:

18 15 16 12 11

Thanks!

图片转代码服务由CSDN问答提供 功能建议

我从数据库中回显一些数字并仅显示带有foreach的数字。 我现在想要计算这些数字的总和。

  $ test = str_replace('\\','',$ orderDetails ['jsonData']); 
 $  bonbonOrders = unserialize($ test); 
 
foreach($ bonbonOrders as $ bonbonOrder){
 foreach($ bonbonOrder as $ bonbons){
 echo $ bonbons ['gewicht']; 
} 
} 
    
 
 

我尝试了几件事,但我真的不知道如何计算它们。

示例的输出可以是 :

  18 15 16 12 11 
   
 
 

谢谢!

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • duanbipu7601 2016-06-08 14:58
    最佳回答

    This depends how you are getting those numbers from your database. However, since you are deserializing something I will assume that it cannot be done in a simple SQL query.

    The following code should echo out the total of all of the numbers.

    $test = str_replace('\\', '', $orderDetails['jsonData']);
    $bonbonOrders = unserialize($test);
    
    $nums = array();
    foreach($bonbonOrders as $bonbonOrder){
        foreach($bonbonOrder as $bonbons){
            $nums[] =$bonbons['gewicht']; 
        }
    }
    $total = array_sum($nums);
    echo $total;
    

    Achieved by adding all of the numbers to an array, and calling array_sum on the final array.

    Another alternative would have been to create $total = 0 before the foreach and to simply increment it as you get access to each number.

    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题