I am trying to sort an associative array by following this scheme:
- Sort by 'qt': positives first, non-positives after. Magnitude does not matter, only sign.
- In positive part: sort by sa DESC
- In negative part: sort by sa DESC
I managed to have the desired result but by tinkering :
$array = [
[
"id" => 1,
"qt" => 1000,
"sa" => 50
],
[
"id" => 2,
"qt" => 0,
"sa" => 50
],
[
"id" => 3,
"qt" => 0,
"sa" => 350
],
[
"id" => 4,
"qt" => 5000,
"sa" => 250
],
[
"id" => 5,
"qt" => 10,
"sa" => 9000
]
];
$p_qty = array();
$n_qty = array();
foreach ($array as $e) {
if($e['qt'] <= 0){ array_push($n_qty, $e); }
else { array_push($p_qty, $e); }
}
usort($p_qty, function($a, $b){
return
$a['sa'] == $b['sa'] ? (
$a['sa'] == $b['sa'] ? 0 : (
$a['qt'] < $b['qt'] ? 1 : -1
)
) : (
$a['sa'] < $b['sa'] ? 1 : -1
);
});
usort($n_qty, function($a, $b){
return
$a['sa'] == $b['sa'] ? (
$a['sa'] == $b['sa'] ? 0 : (
$a['qt'] < $b['qt'] ? 1 : -1
)
) : (
$a['sa'] < $b['sa'] ? 1 : -1
);
});
I get the wanted result: ID [5, 4, 1, 3, 2]
Is there a simple to do the wanted result in a unique usort
function ?
$p_qty = [ [ id=5, qt=10, sa=5000 ], [ id=4, qt=5000, sa=250 ], [ id=1, qt=1000, sa=50 ] ]; $n_qty = [ [ id=3, qt=0, sa=350 ], [ id=2, qt=0, sa=50 ] ];
And for some improvements, I'd like to get this result :[ [ id=5, qt=10, sa=5000 ], [ id=4, qt=5000, sa=250 ], [ id=1, qt=1000, sa=50 ], [ id=3, qt=0, sa=350 ], [ id=2, qt=0, sa=50 ] ];
\$\endgroup\$qt
value possibly be negative in your business logic? Or when you say "negative", do you more accurately mean "non-positive" (zero). Assumingqt
means "quantity", is it possible to have a negative quantity? \$\endgroup\$