2017-06-21 42 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