JSON删除不需要的字符

时间:2018-11-22 09:30:25

标签: php json

想要从输出中删除括号和逗号,这是一个json数据,我该怎么办?  萨吉德中期成绩

[
    {
        "Englsih": "60"
    },
    {
        "Science": "55"
    },
    {
        "Arabic": "90.5"
    },
    {
        "Math": "60.3"
    }
]

总分= 265.8

2 个答案:

答案 0 :(得分:0)

使用json_decode将字符串组成一个数组,然后循环该数组以求和。

$sum=0;
$arr = json_decode($str, true);
foreach($arr as $class){
    foreach($class as $score) $sum += $score;

}
echo $sum; //265.8

https://3v4l.org/IXfcv


您还可以使用preg_match_all和array_sum。
匹配所有数字并求和输出数组

$str = preg_match_all("/[\d.]+/", $str, $m);
echo array_sum($m[0]); // 265.8

https://3v4l.org/RnbbB

答案 1 :(得分:-1)

像这样:

$json = '[
    {
        "Englsih": "60"
    },
    {
        "Science": "55"
    },
    {
        "Arabic": "90.5"
    },
    {
        "Math": "60.3"
    }
]';
$arr = json_decode($json);
$sum array_sum(arr);
相关问题