Sort array - that specific values will be first

后端 未结 4 1137
失恋的感觉
失恋的感觉 2020-12-21 08:20

I have a array. for example:

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

i want to sort the array that first will be \"orange\

4条回答
  •  暖寄归人
    2020-12-21 08:37

    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

提交回复
热议问题