Given that I have a hash of identifier (key) and countries (values) sorted alphabetically, what is the best way to bubble the entry to the top of the stack?

This is an example php, but an algorithm for any language. What I specifically want to do is overshadow the US and Canada at the top of the list. Here is an example array shortened for brevity.

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

The identifier shall remain intact. Therefore, to make them -1 or -2, unfortunately, will not succeed.

+3
source share
5 answers

, , - DisplayOrder - . , , 1... DisplayOrder, . - , , .

-

+6

, . SELECT, , - .

, . Java , StringComparator, compare(), , ( ), , .

, , . - , , . .

[] , , , , . -2, -1, ID ? PHP 11 , , .

+1
$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";
}

:

80 => USA
0 => - select -
1 => Afghanistan
2 => Albania
3 => Algeria
+1

, "" . , , , - :

$countries = array(
  0 => '-- SELECT --',
  1 => 'Afghanistan',
  2 => 'Albania',
  3 => 'Algeria',
  4 => 'American Samoa',
  5 => 'Andorra',
  22 => 'Canada',
  44 => 'United States',);

# tell what should be upfront (by id)
$favourites = array(0, 44, 22);

# add favourites at first
$ordered = array();
foreach($favourites as $id)
{
    $ordered[$id] = $countries[$id];
}

# add everything else
$ordered += array_diff_assoc($countries, $ordered);

# result
print_r($ordered);

0

, . .

array_unshift($queue, "United States", "Canada");
print_r($queue);

array_unshift - .

0
source

Source: https://habr.com/ru/post/1696683/


All Articles