我正在尝试使用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 :(得分:16)
以下行有错误:
$arr2 = array_multisort($mar, array('wek'=>SORT_ASC));
您正在尝试将返回结果存储到数组中,但是array_multisort返回的布尔值不是已排序的数组:
执行此操作以排序多维数组 $ mar :
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);
$ mar 数组现在在上述操作之后进行排序..
答案 1 :(得分:2)
为了能够使用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);