按州,城市排序数组

时间:2011-07-14 16:04:57

标签: php arrays sorting

我有一个城市和州的PHP数组。我希望最终结果按州按字母顺序排序,然后按城市排序。

开始于:

Location[0]['state'] => 'Ohio', 
Location[0]['city'] => 'Columbus', 
Location[1]['state'] => 'Illinois', 
Location[1]['city'] => 'Chicago', 
Location[2]['state'] => 'Ohio', 
Location[2]['city'] => 'Cleveland', 
Location[3]['state'] => 'Illinois', 
Location[3]['city'] => 'Springfield'

最终结果应按如下方式排序:

Location[0]['state'] => 'Illinois', 
Location[0]['city'] => 'Chicago', 
Location[1]['state'] => 'Illinois', 
Location[1]['city'] => 'Springfield', 
Location[2]['state'] => 'Ohio', 
Location[2]['city'] => 'Cleveland', 
Location[3]['state'] => 'Ohio', 
Location[3]['city'] => 'Columbus'

3 个答案:

答案 0 :(得分:3)

function a($a,$b){
    if($a['state']>$b['state'])return 1;
    if($a['state']<$b['state'])return -1;
    if($a['city']>$b['city'])return 1;
    if($a['city']<$b['city'])return -1;
    return 0;
}

usort($Location,'a');

从5.3开始:

usort($Location,function($a,$b){
    if($a['state']>$b['state'])return 1;
    if($a['state']<$b['state'])return -1;
    if($a['city']>$b['city'])return 1;
    if($a['city']<$b['city'])return -1;
    return 0;
});

ADDED :使用strcmp

更容易
function a($a,$b){
    $c=strcmp($a['state'],$b['state']);
    if($c)return $c;
    return strcmp($a['city'],$b['city']);
}

答案 1 :(得分:0)

function sort_array(&$array, $by, $order = 'DESC')
{
    $new_array = $sortable_array = array();

    foreach ($array as $k => $v)
    {
        if (is_array($v))
        {
            foreach ($v as $k2 => $v2)
            {
                if ($k2 == $by)
                {
                    $sortable_array[$k] = $v2;
                }
            }
        }
        else
        {
            $sortable_array[$k] = $v;
        }
    }

    ($order == 'DESC') ? arsort($sortable_array) : asort($sortable_array);

    foreach ($sortable_array as $k => $v)
    {
        $new_array[$k] = $array[$k];
    }

    $array = $new_array;
}

答案 2 :(得分:0)

不是我最好的工作,但它运作良好:

// split the city and elements into their own arrays
foreach ($locations as $location) {
  $states[] = $location['State'];
  $cities[] = $location['City'];
}

// array_multisort sorts the first array given, 
// and sorts the second array to keep its elements
// in the same order relative to the first array
array_multisort($states, $cities);

//reset the $locations array
$locations = array();

// recreate the $locations array from the two
// separate state and city arrays
for ($i = 0; $i < count($states); $i++) {
  $locations[] = array('State' => $states[$i], 'City' => $cities[$i]);
}