我有一个列,其值是 JSON 格式:
Row 1: {"id":"1","name":"shoe","price":"1000"}
Row 2: {"id":"2","name":"bag","price":"2000"}
etc....
我想要这个 JSON 格式列中所有价格的总和。我怎样才能实现这个目标?请注意,我可以使用 PHP 来解析 JSON 值,但问题是我应该对所有这些行进行 Group Concat(我想要一行)。例如:
{"id":"1","name":"shoe","price":"1000"}||{"id":"2","name":"bag","price":"2000"}||...
||
是分离器。我担心的是,假设我们有 10,000 行! MySQL 是否支持太长的字符串,或者这样做是否有效?
有什么其他方法可以这样做?
最佳答案
试试这个:
$json = '[{"id":"1","name":"shoe","price":"1000"} ,{"id":"2","name":"bag","price":"2000"}]'; // Assign Json to var
$jsonObj = json_decode($json); // Decode the JSON to OBJ
// Now loop and find the SUM
$total = 0;
foreach ($jsonObj as $item){
$total =+ $item->price;
}
// Print the SUM
echo "Sum : $total";
关于php - json 格式值的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26987875/