batz batz - 1 year ago 71
PHP Question

Sort array - that specific values will be first

I have a array. for example:

array("Apple", "Orange", "Banana", "Melon");


i want to sort the array that first will be "orange", "melon". and the array will be

array( "Orange" , "Melon","Apple","Banana");


i looked in PHP sort functions, didn't find a s sort function to do it.

what is the right way to do it.

thank you

Answer Source

Another solution; using a custom function to move an element to the beginning of an array

function __unshift(&$array, $value){
    $key = array_search($value, $array);
    if($key) unset($array[$key]);
    array_unshift($array, $value);  
    return $array;
}

$a = array("Apple", "Orange", "Banana", "Melon");
__unshift($a, "Melon");
__unshift($a, "Orange");
print_r($a);

Output:

Array
(
    [0] => Orange
    [1] => Melon
    [2] => Apple
    [3] => Banana
)

Demo

Or you may use the following to reorder an array using another array having reordered index

function __reorder(&$a, &$b){
    $c = array();
    foreach($b as $index){
        array_push($c, $a[$index]);
    }
    return $c;
}

// the original array
$a = array("Apple", "Orange", "Banana", "Melon");
// an array with reordered index 
$b = array(1, 3, 0, 2);
$c = __reorder($a, $b);
print_r($c);

Demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download