I need to sort an array of items by score, then by date without moving the rows where the lock value is greater than zero.
In other words, the rows with lock=3
and lock=5
should stay in the same/original position after the sorting is finished.
[
['id' => 7867867, 'lock' => 0, 'score' => 322, 'strtotime' => 16614713],
['id' => 7867867, 'lock' => 0, 'score' => 444, 'strtotime' => 16614613],
['id' => 7867867, 'lock' => 3, 'score' => 0, 'strtotime' => 16613713],
['id' => 7867867, 'lock' => 0, 'score' => 11, 'strtotime' => 16612713],
['id' => 7867867, 'lock' => 5, 'score' => 0, 'strtotime' => 16614413],
['id' => 7867867, 'lock' => 0, 'score' => 42, 'strtotime' => 16614113],
['id' => 7867867, 'lock' => 0, 'score' => 22, 'strtotime' => 16614013],
]
I use the following code to sort on score
than strtotime
, but this affects the rows that shouldn't move.
usort($array, function ($a, $b) {
if ( $a->score == $b->score ) { //score are same
return $b->strtotime <=> $a->strtotime; //sort by strtotime
}
return $b->score <=> $a->score; //else sort by score
});
My desired output is:
[
['id' => 7867867, 'lock' => 0, 'score' => 11, 'strtotime' => 16612713],
['id' => 7867867, 'lock' => 0, 'score' => 22, 'strtotime' => 16614013],
['id' => 7867867, 'lock' => 3, 'score' => 0, 'strtotime' => 16613713],
['id' => 7867867, 'lock' => 0, 'score' => 42, 'strtotime' => 16614113],
['id' => 7867867, 'lock' => 5, 'score' => 0, 'strtotime' => 16614413],
['id' => 7867867, 'lock' => 0, 'score' => 322, 'strtotime' => 16614713],
['id' => 7867867, 'lock' => 0, 'score' => 444, 'strtotime' => 16614613],
]