开发者

Sort Array by State, City

开发者 https://www.devze.com 2023-03-20 03:42 出处:网络
I have a PHP Array of Cities and States. I want the end result to be sorted alphabetically by State and then by City.

I have a PHP Array of Cities and States. I want the end result to be sorted alphabetically by State and then by City.

Start With:

Location[0]['state'] => 'Ohio', 
Location[0]['city'] => 'Columbus', 
Location[1]['state'] => 'Illinois', 
Location[1]['city'] => 'Chicago', 
Location[2]['state'] => 'Ohi开发者_开发技巧o', 
Location[2]['city'] => 'Cleveland', 
Location[3]['state'] => 'Illinois', 
Location[3]['city'] => 'Springfield'

The end result should be sorted like this:

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'


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');

as of 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: it is more easy with strcmp

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


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;
}


Not my best work, but it works well enough:

// 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]);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消