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的顺序排列
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的顺序排列
问题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} 秒";4 回答973 阅读
1 回答653 阅读✓ 已解决
2 回答627 阅读
605 阅读
不知道是不是你想要的