我遇到了一个问题:我试图在json中将所有值相同的“id”加起来示例:
[{id: "100002475575341", name: "N1", point: "2"},
{id: "100002993363229", name: "N2", point: "2"},
{id: "100002993363229", name: "N2", point: "2"},
{id: "100002475575341", name: "N1", point: "2"}]
和预期结果:
[{id: "100002475575341", name: "N1", point: "4"},
{id: "100002993363229", name: "N2", point: "4"}]
注意:我通过在索引名称周围添加引号,将JSON字符串更改为有效
将JSON解码为数组,然后循环它。将它添加到由$results
索引的name
数组中。如果元素存在,请将这些点一起添加。如果它不存在,请创建它。
$json = '[{"id": "100002475575341", "name": "N1", "point": "2"},
{"id": "100002993363229", "name": "N2", "point": "2"},
{"id": "100002993363229", "name": "N2", "point": "2"},
{"id": "100002475575341", "name": "N1", "point": "2"}]';
$array = json_decode($json);
$result = [];
foreach ($array as $a) {
if (isset($result[$a->name])) {
$result[$a->name]->point += $a->point;
} else {
$result[$a->name] = $a;
}
}
$output = json_encode(array_values($result));
我以你的代码为例,你可以试试这个
注意:我更改了您的JSON,因为它是无效的JSON格式。
<?php
$jsonString = '[{
"id": "100002475575341",
"name": "N1",
"point": "2"
},
{
"id": "100002993363229",
"name": "N2",
"point": "2"
},
{
"id": "100002993363229",
"name": "N2",
"point": "2"
},
{
"id": "100002475575341",
"name": "N1",
"point": "2"
}
]';
$jsonDecoded = json_decode($jsonString, true);
$res = [];
foreach ($jsonDecoded as $value) {
if(array_key_exists($value['id'], $res)){
$res[$value['id']] += $value['point'];
}else{
$res[$value['id']] = $value['point'];
}
}
print_r($res);
?>