我有一个列,其值为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是否支持太长的字符串,或者这样做是否有效?
有没有其他方法可以做到这一点?
答案 0 :(得分:2)
试试这个:
$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";