2015-04-01 78 views
0

JSON数据说我得到了以下JSON:“总结”用PHP

{ 
users: [ 
{ 
    qnt: "3", 
    post: "j8v2g5", 
    contact: "[email protected]", 
    id: "1" 
}, 
{ 
    qnt: "10", 
    post: "xxxyyy", 
    contact: "[email protected]", 
    id: "6" 
}, 
{ 
    qnt: "3", 
    post: "xxxyyy", 
    contact: "[email protected]", 
    id: "4" 
} 
] 
} 

我想用同样postusers所有的孩子有自己的qnt加在一起,并从最终结果中删除contactid

我想要的结果看起来像这样:

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

你试过了什么?如果你被困在某个地方,我们会很乐意提供帮助,但是你不能指望我们为你做所有的工作!除非我可以向您发送一张发票;-) – Pevara 2015-04-01 22:52:14

+0

通过json_decode()将其转换为数组,然后像array_walk一样构建一个数组。如果post是in_array,则将qnt添加到qnt。然后通过json_encode()对结果进行编码。 – 2015-04-01 22:55:38

+0

@Pevara谢谢你的帮助,我不知道如果没有你,我会怎样做。:)现在,如果你不能,甚至不考虑帮助 - 不要麻烦评论。 – 2015-04-01 22:56:59

回答

2

你会probabely被recieveing从某处$myJson然后你就可以返回$rsultsJson。我建议把这整个事情放在一个函数或类的方法中。

$myJson = '{"users": [{ "qnt": "3", "post": "j8v2g5", "contact": "[email protected]", "id": "1" }, { "qnt": "10", "post": "xxxyyy", "contact": "[email protected]", "id": "6" }, { "qnt": "3", "post": "xxxyyy", "contact": "[email protected]", "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); 
+0

非常棒的伴侣:) – 2015-04-01 23:24:31