用PHP汇总“JSON数据”

时间:2015-04-01 22:48:49

标签: php json

说我得到了以下JSON:

{
users: [
{
  qnt: "3",
  post: "j8v2g5",
  contact: "foo@bar.com",
  id: "1"
 },
 {
  qnt: "10",
  post: "xxxyyy",
  contact: "foo@foo.net",
  id: "6"
 },
 {
  qnt: "3",
  post: "xxxyyy",
  contact: "bar@foo.org",
  id: "4"
 }
]
}

我希望users的所有同一post的孩子将qnt添加到一起,并从最终结果中删除contactid。< / p>

我希望结果看起来像这样:

{
users: [
 {
  qnt: "3",
  post: "j8v2g5"
 },
 {
  qnt: "13",
  post: "xxxyyy"
 }
]
}

1 个答案:

答案 0 :(得分:2)

您可能会从某处收到$myJson,然后您可以返回$rsultsJson。我建议把这整件事放在函数或类方法中。

$myJson = '{"users": [{  "qnt": "3",  "post": "j8v2g5",  "contact": "foo@bar.com",  "id": "1" }, {  "qnt": "10",  "post": "xxxyyy",  "contact": "foo@foo.net",  "id": "6" }, {  "qnt": "3",  "post": "xxxyyy",  "contact": "bar@foo.org",  "id": "4" }]}';
$usersObject=json_decode($myJson);
$usersArray = $usersObject->users;
$postCount = array();

foreach ($usersArray as $user) {
    if (array_key_exists($user->post, $postCount)) {
        $postCount[$user->post] += $user->qnt;
    } else {
        $postCount[$user->post] = $user->qnt;
    }   

}

$results = new stdClass();
$results->users = array();
foreach ($postCount as $post => $count) {
    $user = new stdClass();
    $user->qnt = $count;
    $user->post = $post;    
    $results->users[] = $user;
}

$rsultsJson = json_encode($results);