2015-04-01 31 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