排序数组-该特定值将是第一个 [英] Sort array - that specific values will be first

查看:136
本文介绍了排序数组-该特定值将是第一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组.例如:

   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");

我查看了PHP的排序函数,但没有找到可以执行此操作的s排序函数.
什么是正确的方法.
谢谢

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

推荐答案

另一个解决方案;使用自定义函数将元素移动到数组的开头

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);

输出:

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

演示

或者您可以使用以下内容使用另一个具有重新排序的索引的数组来重新排序一个数组

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);

演示

这篇关于排序数组-该特定值将是第一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆