Php 合并三个数组并按位置字段对新数组排序
我有3个数组,我正在使用Php 合并三个数组并按位置字段对新数组排序,php,Php,我有3个数组,我正在使用array\u merge函数合并它们。这是正确的结果;一个数组正在附加下一个数组 但是我想根据位置字段显示我的数组 $this->array1 = $this->function1(); $this->array2 = $this->function2(); $this->array3 = this->function3(); $this->result= array_merge( $this->array1,$this-
array\u merge
函数合并它们。这是正确的结果;一个数组正在附加下一个数组
但是我想根据位置
字段显示我的数组
$this->array1 = $this->function1();
$this->array2 = $this->function2();
$this->array3 = this->function3();
$this->result= array_merge( $this->array1,$this->array2,this->array3);
我从上面的数组合并中得到以下结果:-
Array
(
[0] => Array
(
[id_custom] => 1
[id_product] => 1904
[position] => 1
[active] => 1
)
[1] => Array
(
[id_custom] => 6
[id_product] => 1386
[position] => 3
[active] => 1
)
[2] => Array
(
[id_custom] => 5
[id_product] => 2008
[position] => 2
[active] => 1
)
[3] => Array
(
[id_custom] => 8
[id_product] => 0
[id_category] => 0
[position] => 99
[active] => 1
)
)
但我希望数组根据位置显示,如:-
Array
(
[0] => Array
(
[id_custom] => 1
[id_product] => 1904
[position] => 1
[active] => 1
)
[2] => Array
(
[id_custom] => 5
[id_product] => 2008
[position] => 2
[active] => 1
)
[1] => Array
(
[id_custom] => 6
[id_product] => 1386
[position] => 3
[active] => 1
)
[3] => Array
(
[id_custom] => 8
[id_product] => 0
[id_category] => 0
[position] => 99
[set_devices] =>
[active] => 1
)
)
知道如何根据位置字段显示数组吗?要根据字段对数组进行排序,需要使用usort
功能(请参阅)
这允许您编写一个自定义比较函数,以便在给定数组中的两个元素时,您可以判断哪一个应该先出现
在您的情况下,可能是这样的:
function comparePosition($a, $b)
{
if ($a['position'] == $b['position']) {
return 0;
}
if ($a['position'] < $b['position']) {
return -1;
}
return 1;
}
usort($this->array1, 'comparePosition');
函数比较($a,$b)
{
如果($a['position']=$b['position']){
返回0;
}
如果($a['position']<$b['position']){
返回-1;
}
返回1;
}
usort($this->array1,'comparePosition');
你想通过id\u custom
字段更新数组顺序吗?请查看usort()函数@binaryborts我想通过位置字段更新数组顺序,因为在每个select查询中,我都是通过ASC位置显示顺序,但合并后数组位置不正确,工作正常!!!谢谢