2017-06-21 86 views
-2

我有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字段的数组?

+0

要更新由'id_custom'场的阵列的订单? –

+0

看看usort()函数 http://php.net/usort – verhie

+0

@BinaryBrackets我想通过位置字段更新我的数组顺序,因为在每个select查询中,我显示ASC位置的顺序,但合并后的数组位置不正确 – bhatt

回答

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'); 
+0

,其工作正常!谢谢 – bhatt