phparrayssortingassociative-arraycustom-sort

How to prioritize certain elements by value while sorting an associative array?


I have an array of countries that I will be using in a select menu:

array(
    [0] => " -- Select -- "
    [1] => "Afghanistan"
    [3] => "Albania"
    [4] => "Algeria"
    [39] => "Canada"
    [47] => "USA"
    //etc...
)

I want to copy create copies of the Canada and USA entries and place them at the front of my array. So the array should end up looking like this:

array(
    [0] => " -- Select -- "
    [47] => "USA"
    [39] => "Canada"
    [1] => "Afghanistan"
    [3] => "Albania"
    [4] => "Algeria"
    //etc...
)

The array keys correspond to their ID in the database, so I can't change the keys. How can I achieve this?

Solution

I realized that this is not possible. When you try to set a value in an array with a duplicate key, it overwrites the first key. I came up with a different solution, but have accepted the highest rated answer.


Solution

  • Instead of using a one dimensional array as id=> value, you can use a two dimensional array, such as

    $countries = array(
        0 => array(
                       'country_id' => 47,
                       'country' => 'USA'
                   ),
        1 => array(
                       'country_id' => 39,
                       'country' => 'Canada'
                   ),
        2 => array(
                       'country_id' => 1,
                       'country' => 'Afghanistan'
                   ),
        ......
    );