基于数组值

时间:2015-11-27 12:04:58

标签: php 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 个答案:

答案 0 :(得分: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;
});