2014-03-07 70 views
2

我試圖使用排序功能array_multisort()它的子陣列的基礎上的陣列......在array_multisort():數組大小不一致

雖然試圖;

print_r($mar); echo '<br>'; 
$arr2 = array_multisort($mar, array('wek'=>SORT_ASC)); 
print_r($arr2); 

得到錯誤array_multisort(): Array sizes are inconsistent

輸出排序前是

Array ( 
    [0] => Array ([dat] => 1 [wek] => 5 [mac] => A100 [mcr] => #00c8ff) 
    [1] => Array ([dat] => 2 [wek] => 9 [mac] => A100 [mcr] => #00c8ff) 
    [2] => Array ([dat] => 5 [wek] => 13 [mac] => A100 [mcr] => #00c8ff) 
    [3] => Array ([dat] => 5 [wek] => 6 [mac] => A101 [mcr] => #ff8800) 
    [4] => Array ([dat] => 13 [wek] => 17 [mac] => A100 [mcr] => #00c8ff) 
    [5] => Array ([dat] => 20 [wek] => 21 [mac] => A100 [mcr] => #00c8ff) 
    [6] => Array ([dat] => 8 [wek] => 14 [mac] => A101 [mcr] => #ff8800) 
) 

我需要的是:

Array ( 
    [0] => Array ([dat] => 1 [wek] => 5 [mac] => A100 [mcr] => #00c8ff) 
    [3] => Array ([dat] => 5 [wek] => 6 [mac] => A101 [mcr] => #ff8800) 
    [1] => Array ([dat] => 2 [wek] => 9 [mac] => A100 [mcr] => #00c8ff) 
    [2] => Array ([dat] => 5 [wek] => 13 [mac] => A100 [mcr] => #00c8ff) 
    [6] => Array ([dat] => 8 [wek] => 14 [mac] => A101 [mcr] => #ff8800) 
    [4] => Array ([dat] => 13 [wek] => 17 [mac] => A100 [mcr] => #00c8ff) 
    [5] => Array ([dat] => 20 [wek] => 21 [mac] => A100 [mcr] => #00c8ff) 
) 
+0

檢查是如何工作的[在array_multisort(http://www.php.net/manual /fr/function.array-multisort.php)。第三個例子對你有幫助:** array_multisort()需要一個列數組** – Debflav

+0

只需對此進行評論即可。當改爲PHP 7.x時,我遇到了使用PHP 5.x的相同問題,解決了這個問題。 – celsomtrindade

回答

14

有以下行錯誤:

$arr2 = array_multisort($mar, array('wek'=>SORT_ASC)); 

你試圖將返回結果存儲到一個數組,但array_multisort返回布爾值而不是排序數組:

這樣做是爲了排序你的multid imensional陣列$三月

foreach ($mar as $key => $row) 
{ 
    $wek[$key] = $row['wek']; 
}  

// Sort the data with wek ascending order, add $mar as the last parameter, to sort by the common key 

array_multisort($wek, SORT_ASC, $mar); 

$三月陣列現在可以正確排序上面的操作後..

1

爲了能夠使用在array_multisort應重新組織你的陣列。 見的例子#3瀏覽:http://uk1.php.net/array_multisort

或者你可以使用usort,但它會重新編號的鑰匙:

<?php 
$mar =Array (. 
    0 => Array ('dat' => 1, 'wek' => 5, 'mac' => 'A100', 'mcr' => '#00c8ff') , 
    1 => Array ('dat' => 2, 'wek' => 9, 'mac' => 'A100', 'mcr' => '#00c8ff') , 
    2 => Array ('dat' => 5, 'wek' => 13, 'mac' => 'A100', 'mcr' => '#00c8ff') , 
    3 => Array ('dat' => 5, 'wek' => 6, 'mac' => 'A101', 'mcr' => '#ff8800') , 
    4 => Array ('dat' => 13, 'wek' => 17, 'mac' => 'A100', 'mcr' => '#00c8ff'), 
    5 => Array ('dat' => 20, 'wek' => 21, 'mac' => 'A100', 'mcr' => '#00c8ff') , 
    6 => Array ('dat' => 8, 'wek' => 14, 'mac' => 'A101', 'mcr' => '#ff8800') , 
); 

usort($mar, function($a,$b){return $a['wek']-$b['wek'];}); 
print_r($mar);