How can I sort arrays by multiple conditions? array (
'000-00' => array (
'Qty '=> 20,
'Price' => 200
),
'2014-00' => array (
'Qty '=> 10,
'Price' => 100
),
'2014-00' => array (
'Qty '=> 30,
'Price' => 50
)
)
How can I first sort by qty from small to large, and then by Price from large to small.
Reply to discussion (solution)
$a = array( '000-00'=>array( 'qty'=>20, 'price'=>200 ), '0001-00'=>array( 'qty'=>10, 'price'=>100 ), '0002-00'=>array( 'qty'=>30, 'price'=>50 ) );foreach($a as $k=>$v) { $qty[] = $v['qty']; $price[] = $v['price'];}array_multisort($qty, $price, SORT_DESC, $a);print_r($a);
Array( [0001-00] => Array ( [qty] => 10 [price] => 100 ) [000-00] => Array ( [qty] => 20 [price] => 200 ) [0002-00] => Array ( [qty] => 30 [price] => 50 ))
$a = array( '000-00'=>array( 'qty'=>20, 'price'=>200 ), '0001-00'=>array( 'qty'=>10, 'price'=>100 ), '0002-00'=>array( 'qty'=>30, 'price'=>50 ) );foreach($a as $k=>$v) { $qty[] = $v['qty']; $price[] = $v['price'];}array_multisort($qty, $price, SORT_DESC, $a);print_r($a);
Array( [0001-00] => Array ( [qty] => 10 [price] => 100 ) [000-00] => Array ( [qty] => 20 [price] => 200 ) [0002-00] => Array ( [qty] => 30 [price] => 50 ))
This function is really convenient!
Can I ask if there are a few more sub-arrays? it may not work after a few more arrays.
Array (
'000-00' => array (
'Qty '=> 20,
'Price' => 200,
'Status' => 1,
'Lirun' => 0.21,
'Name' => 'sdff ',
),
'2014-00' => array (
'Qty '=> 10,
'Price' => 100,
'Status' => 1,
'Lirun' => 0.22,
'Name' => 'erw ',
),
'2014-00' => array (
'Qty '=> 30,
'Price' => 50,
'Status' => 1,
'Lirun' => 0.23,
'Name' => 'sdfs ',
)
)
Yes. the original variable name must be the same as the name in the array.