合并三个数组并按位置字段对此新数组进行排序

时间:2017-06-21 07:03:39

标签: php

我有3个数组,我将它们与array_merge函数合并。这给出了正确的结果;一个数组附加下一个数组。

但我想根据position字段显示我的数组。

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

)

但是我希望基于postion字段显示数组,如: -

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
        )

)

知道如何根据position字段显示数组吗?

1 个答案:

答案 0 :(得分:0)

要根据字段对数组进行排序,您需要使用usort函数(请参阅http://php.net/manual/en/function.usort.php)。

这允许你编写一个自定义比较函数,这样,给定阵列上的两个元素,你可以告诉哪一个应该是第一个。

在你的情况下,它会是这样的:

function comparePosition($a, $b)
{
    if ($a['position'] == $b['position']) {
        return 0;
    }
    if ($a['position'] < $b['position']) {
        return -1;
    }    
    return 1;
}

usort($this->array1, 'comparePosition');