假设我有几个数组。
$a = array("E", "A", NULL, "D", "C");
$b = array("Dog","Cat","Horse","Bear","Zebra");
$c = array(12, 11, 20, 30, 19);
第一个数组不是必需的数字,可以包含空值。
我想按照第一个顺序对所有3个数组进行排序,即得到
"A", "C", "D", "E", NULL
"Cat", "Zebra", "Bear", "Dog", "Horse"
11, 19, 30, 12, 20
即。元组(" E","狗",12),(" A"," Cat",11),(NULL,&# 34;马",20),(" D","熊",30),(" C"," Zebra" ,19)应该保守。
我不关心空案件会发生什么:可以留在原地或者结束或开始。
答案 0 :(得分:2)
您可以使用array_multisort
根据第一个数组对多个数组进行排序。见下面的例子
$a = array("E", "A", NULL, "D", "C");
$b = array("Dog","Cat","Horse","Bear","Zebra");
$c = array(12, 11, 20, 30, 19);
array_multisort($a, SORT_ASC, SORT_STRING, $b, $c); // $b and $c sorting based on $a
echo "<pre>";
print_r($b);
print_r($c);
答案 1 :(得分:1)
希望我的帖子可以帮到你..我们正在使用两个函数array_combine
和ksort
。 array_combine
会将values
与keys
合并而ksort
将按键排序数组
<?php
ini_set('display_errors', 1);
$a = array(5, 1, 2, 4, 3);
$b = array("Dog","Cat","Horse","Bear","Zebra");
$combined=array_combine($a, $b);
ksort($combined);
print_r($combined);
<强>输出:强>
Array
(
[1] => Cat
[2] => Horse
[3] => Zebra
[4] => Bear
[5] => Dog
)
答案 2 :(得分:1)
你可以制作类似
的数组{{1}}
这是使用array_combine($ a,$ b)实现的 之后,您可以在组合数组上使用ksort。
答案 3 :(得分:1)
使用array_combine
第一个参数作为key
第二个参数被视为value
并使用ksort
根据键对数组进行排序。最后如果想重新排列密钥使用array_values
<?php
$a = array(5, 1, 2, 4, 3);
$b = array("Dog","Cat","Horse","Bear","Zebra");
$join=array_combine($a, $b);
ksort($join);
print_r(array_values($join));
?>
答案 4 :(得分:1)
您可以使用array_combine()
然后ksort()
:
$a = array(5, 1, 2, 4, 3);
$b = array("Dog","Cat","Horse","Bear","Zebra");
$c = array_combine($a, $b);
ksort($c);
var_dump($c);
array (size=5)
1 => string 'Cat' (length=3)
2 => string 'Horse' (length=5)
3 => string 'Zebra' (length=5)
4 => string 'Bear' (length=4)
5 => string 'Dog' (length=3)
答案 5 :(得分:0)
试试这个。 NULL将在数组的开头。
$a = array("E", "A", NULL, "D", "C");
asort($a); // Sort array and maintain index association
echo "<pre>"; print_r($a);
$b = array("Dog","Cat","Horse","Bear","Zebra");
$c = array(12, 11, 20, 30, 19);
foreach($a as $k=>$v){
$b1[] = $b[$k]; //you can also check with isset() whether it exist or not in this array
$c1[] = $c[$k];
}
echo "<pre>"; print_r($b1);
echo "<pre>"; print_r($c1);