views:

132

answers:

4

This is a php example, but an algorithm for any language would do. What I specifically want to do is bubble up the United States and Canada to the top of the list. Here is an example of the array shortened for brevity.

array(
  0 => '-- SELECT --',
  1 => 'Afghanistan',
  2 => 'Albania',
  3 => 'Algeria',
  4 => 'American Samoa',
  5 => 'Andorra',)

Edit: @Leigh The id's need to be intact. So making them -1 or -2 will unfortunately not work.

+1  A: 

My shortcut in similar cases is to add a space at the start of Canada and two spaces at the start of United States. If displaying these as options in a SELECT tag, the spaces are not visible but the sorting still brings them to the front.

However, that may be a little hacky in some contexts. In Java the thing to do would be to extend StringComparator, override the compare() method making the US and Canada special cases, then sort the list (or array) passing in your new comparator as the sort algorithm.

However I would imagine it might be simpler to just find the relevant entries in the array, remove them from the array and add them again at the start. If you are in some kind of framework which will re-sort the array, then it might not work. But in most cases that will do just fine.

[edit] I see that you are using a hash and not an array - so it will depend on how you are doing the sorting. Could you simply put the US into the hash with a key of -2, Canada with -1 and then sort by ID instead? Not having used PHP in anger for 11 years, I don't recall whether it has built-in sorting in its hashes or if you are doing that at the application level.

Leigh Caldwell
A: 

Right now I'm just placing them in the hash before I place the rest of the data in there. Then when I loop over the result set I just skip over them.

mk
+5  A: 

What I usually do in these situations is to add a separate field called DisplayOrder or something similar. Everything defaults to, say, 1... You then sort by DisplayOrder and then the Name. If you want something higher or lower on the list, you can tweak the display order accordingly while keeping your normal IDs as-is.

-- Kevin Fairchild

Kevin Fairchild
+1  A: 
$a = array(
    0 => '- select -',
    1 => 'Afghanistan',
    2 => 'Albania',
    3 => 'Algeria',
    80 => 'USA'
);

$temp = array();
foreach ($a as $k => $v) {
    $v == 'USA'
     ? array_unshift($temp, array($k, $v))
     : array_push($temp, array($k, $v));
}
foreach ($temp as $t) {
    list ($k, $v) = $t;
    echo "$k => $v\n";
}

The output is then:

80 => USA
0 => - select -
1 => Afghanistan
2 => Albania
3 => Algeria
Michał Rudnicki