2014-04-14 344 views
0

我有以下的JSON:PHP排序JSON從最高到最低

 { 
    "ID":"4", 
    "name":"Gil", 
    "likes":0, 
    "Dec":"A Man" 
    }, 
    { 
    "ID":"3", 
    "name":"Yoni", 
    "likes":3, 
    "Dec":"A child" 
    }, 
    { 
    "ID":"6", 
    "name":"Roni", 
    "likes":1, 
    "Dec":"A woman" 
    } 

而且我想基於從heighst到最低喜歡到rearange它這樣的結果將是:

{ 
     "ID":"5", 
     "name":"Roni", 
     "likes":6, 
     "Dec":"A woman" 
     } , 
    { 
     "ID":"3", 
     "name":"Yoni", 
     "likes":3, 
     "Dec":"A child" 
     }, 

{ 
     "ID":"4", 
     "name":"Gil", 
     "likes":0, 
     "Dec":"A Man" 
     } 

我如何在PHP中重新排列它?

+2

隱蔽這個JSON來陣列json_decode(JSON,TRUE);使用一些數組排序函數對它進行排序然後重新創建json。 –

+0

[按值排序多維數組]的可能重複(http://stackoverflow.com/questions/2699086/sort-multi-dimensional-array-by-value) –

回答

1
$json = '[{ 
    "ID":"4", 
    "name":"Gil", 
    "likes":0, 
    "Dec":"A Man" 
}, 
{ 
    "ID":"3", 
    "name":"Yoni", 
    "likes":3, 
    "Dec":"A child" 
}, 
{ 
    "ID":"6", 
    "name":"Roni", 
    "likes":1, 
    "Dec":"A woman" 
}]'; 

$json_arr = json_decode($json, true); 
usort(
    $json_arr, 
    function($a, $b) { 
    if ($a['likes'] == $b['likes']) { 
     return 0; 
    } 
    return ($a['likes'] > $b['likes']) ? -1 : 1; 
}); 
$json = json_encode($json_arr); 
+0

它完美的工作,謝謝。 – gilm501

5

json_decode/json_encodeusort

$array = json_decode($json_string, TRUE); 

usort($array, function($a, $b) { 
    return $a['likes'] - $b['likes']; 
}); 

echo json_encode($array, JSON_PRETTY_PRINT); 

Demo

相關問題