[英]Sorting array of arrays using array_multisort() [Argument #1 is expected to be an array or a sort flag]
我有這個數組數組
foreach($qcatResults as $qcatResult){
...//codes to get stuff
$cats[] = array(
'category_code' => $qcatResult->category_code,
'category' => $qcatResult->category,
'item_count' => $item_count,
'max_qty' => (int)$max_qty
);
}
var_dump($cats);
這將導致類似
array(34) {
[0]=> array(4) { ["category_code"]=> string(2) "BB" ["category"]=> string(0) ""
["item_count"]=> string(1) "1" ["max_qty"]=> int(12000) }
[1]=> array(4) { ["category_code"]=> string(2) "AK" ["category"]=> string(6) "Anklet"
["item_count"]=> string(1) "1" ["max_qty"]=> int(6) }
[2]=> array(4) { ["category_code"]=> string(3) "BAC" ["category"]=> string(15) "Bag Accessories"
["item_count"]=> string(1) "2" ["max_qty"]=> int(352) }
[3]=> array(4) { ["category_code"]=> string(2) "WB" ["category"]=> string(4) "Bags"
["item_count"]=> string(1) "9" ["max_qty"]=> int(6290) }
[4]=> array(4) { ["category_code"]=> string(2) "AB" ["category"]=> string(20) "Bathroom Accessories"
["item_count"]=> string(2) "19" ["max_qty"]=> int(325) }
[5]=> array(4) { ["category_code"]=> string(2) "BK" ["category"]=> string(4) "Book"
["item_count"]=> string(2) "40" ["max_qty"]=>int(27291) }...
}
我想按max_qty
降序對$cats
進行排序,但是array_multisort
發出錯誤Message: array_multisort(): Argument #1 is expected to be an array or a sort flag
我有這個用法array_multisort()
:
var_dump(array_multisort($max_qty, SORT_DESC, $cats));
我認為usort()可以為您解決問題:
$cats=[
["category_code"=>"BB","category"=>"","item_count"=>"1","max_qty"=>12000],
["category_code"=>"AK","category"=>"Anklet","item_count"=>"1","max_qty"=>6],
["category_code"=>"BAC","category"=>"Bag Accessories","item_count"=>"2","max_qty"=>352],
["category_code"=>"WB","category"=>"Bags","item_count"=>"9","max_qty"=>6290],
["category_code"=>"AB","category"=>"Bathroom Accessories","item_count"=>"19","max_qty"=>325],
["category_code"=>"BK","category"=>"Book","item_count"=>"40","max_qty"=>27291]
];
usort($cats,function($a,$b){
return $b['max_qty']-$a['max_qty'];
});
var_export($cats);
輸出:
array (
0 =>
array (
'category_code' => 'BK',
'category' => 'Book',
'item_count' => '40',
'max_qty' => 27291,
),
1 =>
array (
'category_code' => 'BB',
'category' => '',
'item_count' => '1',
'max_qty' => 12000,
),
2 =>
array (
'category_code' => 'WB',
'category' => 'Bags',
'item_count' => '9',
'max_qty' => 6290,
),
3 =>
array (
'category_code' => 'BAC',
'category' => 'Bag Accessories',
'item_count' => '2',
'max_qty' => 352,
),
4 =>
array (
'category_code' => 'AB',
'category' => 'Bathroom Accessories',
'item_count' => '19',
'max_qty' => 325,
),
5 =>
array (
'category_code' => 'AK',
'category' => 'Anklet',
'item_count' => '1',
'max_qty' => 6,
),
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.