把数组里的数按照指定的顺序重新排序

1 把数组[1,0,9,3,7]排序为[0,1,3,7,9]

2 $a = array('b','a','e','c');
$b = array('a','b','c','d','e','f');
将$b按$a的顺序排列

阅读 12.3k
4 个回答

不知道是不是你想要的

$arr1 = [0,1,3,7,9];

$arr2 = [1,0,9,3,7];

$arr3 = [];

for ($i=0; $i < count($arr1); $i++) { 
    for ($j=0; $j < count($arr2); $j++) { 
        if ($arr2[$j] == $arr1[$i]) {
            $arr3[$i] = $arr2[$j];
        }
    }
}

var_dump($arr3);
$a = array('a','b','c','d','e','f');

$b = array('b','a','e','c');

$c = [];

for ($i=0; $i < count($b); $i++) { 
    for ($j=0; $j < count($a); $j++) { 
        if ($a[$j] == $b[$i]) {
            $c[$i] = $a[$j];
        }
    }
}

var_dump($c);

问题1:

$a = [1,0,9,3,7];
sort($a);
var_dump($a);

问题2:

$a = array('c','a','h','b');
$b = array('a','b','c','d','e','f', 'h', 'g');
$c = array_intersect($a, $b);
$d = array_diff($b, $a);
$e = array_merge($c, $d);
var_dump($e);

最简单的方法是使用php内置函数sort(),没必要写那么多循环

PHP - 数组的排序函数:
1.sort() - 以升序对数组排序
2.rsort() - 以降序对数组排序
3.asort() - 根据值,以升序对关联数组进行排序
4.ksort() - 根据键,以升序对关联数组进行排序
5.arsort() - 根据值,以降序对关联数组进行排序
6.krsort() - 根据键,以降序对关联数组进行排序

这里使用sort()函数

<?php
$numbers=array(3,5,1,22,11);
sort($numbers);
print_r($numbers);
?>

输出

Array
(
    [0] => 1
    [1] => 3
    [2] => 5
    [3] => 11
    [4] => 22
)
<?php
$numbers=array('a','c','b','e','d');
sort($numbers);

$arrlength=count($numbers);
for($x=0;$x<$arrlength;$x++)
   {
   echo $numbers[$x];
   echo "<br>";
   }
?>

输出

a
b
c
d
e

参考PHP 数组排序

<?php
//这里做下已知道的两个方法的时间消耗的对比:方法一更优
$a = array('c','a','h','b');
$b = array('a','b','c','d','e','f', 'h', 'g');

//1.使用内置函数
$stime=microtime(true);
for($i=0;$i<10000;$i++){
    $c = array_intersect($a, $b);
    $d = array_diff($b, $a);
    $e = array_merge($c, $d);
}
var_dump($e);
$etime=microtime(true);
$total=$etime-$stime;   //计算差值
echo "<br />当前页面执行时间为:{$total} 秒";

//2.使用map
$stime1=microtime(true);
for($i=0;$i<10000;$i++){
    $map=array_flip($a);
    $max_index=count($a);
    foreach ($b as $value){
        if(isset($map[$value])){
            $result[$map[$value]]=$value;
        }else{
            $result[++$max_index]=$value;
        }
    }
    ksort($result);
    $result=array_values($result);
}
var_dump($result);
$etime1=microtime(true);
$total1=$etime1-$stime1;   //计算差值
echo "<br />当前页面执行时间为:{$total1} 秒";
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题