2015-11-27 43 views
1

我有一個JSON數組這樣排序基於陣列的JSON數組值

$countries = [ 
     { 
      "id": "1", 
      "country_name": "Afghanistan", 
     }, 
     { 
      "id": "2", 
      "country_name": "Albania", 
     }, 
     { 
      "id": "3", 
      "country_name": "Algeria", 
     }, 
     { 
      "id": "4", 
      "country_name": "American Samoa", 
     }  
     .. 
     .. 
     .. 
     { 
      "id": "50", 
      "country_name": "Zimbabwe", 
     } 
];  

以下數組包含,我需要排序的國家名單頂部

$top_countries = ['United States', 'United Kingdom', 'German']; 

什麼是按如下方式排列上述陣列的最佳方法:

$countries = [ 
     { 
      "id": "30", 
      "country_name": "United States", 
     }, 
     { 
      "id": "31", 
      "country_name": "United Kingdom", 
     }, 
     { 
      "id": "20", 
      "country_name": "German", 
     }, 
     { 
      "id": "1", 
      "country_name": "Afghanistan", 
     }, 
     { 
      "id": "2", 
      "country_name": "Albania", 
     }, 
     { 
      "id": "3", 
      "country_name": "Algeria", 
     }, 
     { 
      "id": "4", 
      "country_name": "American Samoa", 
     }  
     .. 
     .. 
     .. 
     { 
      "id": "50", 
      "country_name": "Zimbabwe", 
     } 
]; 
+1

'json_decode()'+'uasort()'+'json_encode()' – Calimero

+0

沒有解碼,我不認爲php支持排序json,所以,解碼json並轉換爲數組,進行必要的排序操作,然後再次將其轉換爲json。 –

回答

2
// index "value" of country by name 
$top = array_flip($top_countries); 

usort($countries, function($a, $b) use ($top) { 
    // get "value" for each country, if it is in index 
    $aValue = isset($top[$a->country_name])?$top[$a->country_name]:-1; 
    $bValue = isset($top[$b->country_name])?$top[$b->country_name]:-1; 

    if ($aValue == $bValue) { 
     // preserve "original order", assuming they were ordered by id 
     return $a->id < $b->id ? -1 : 1; 
    } 
    return $aValue < $bValue ? 1:-1; 
}); 
+0

太棒了!有用!請在翻轉之前更新您需要倒轉陣列的答案。 :) – Asik

+0

另外,將$ a-> country_name更改爲$ a ['country_name'] – Asik

+0

@Asik,我在閉包的return語句中將它恢復爲1和-1。它比反向'$ top_countries'便宜 –