I need to sort an array based on how much the item was sold. Then I need to sort it so that the priority (anything above zero) is moved to the top. The issue I'm having is that when I do the second sort (step 3) it unsort the sort from step 2.
Step 1: I have an array:
array(
array(
'title' => 'A',
'priority' => 0,
'sold_count' => 44
),
array(
'title' => 'B',
'priority' => 2,
'sold_count' => 0
),
array(
'title' => 'C',
'priority' => 1,
'sold_count' => 3
),
array(
'title' => 'D',
'priority' => 0,
'sold_count' => 33
),
)
Step 2: I sort it based on sold_count and get:
array(
array(
'title' => 'A',
'priority' => 0,
'sold_count' => 44
),
array(
'title' => 'D',
'priority' => 0,
'sold_count' => 33
),
array(
'title' => 'C',
'priority' => 1,
'sold_count' => 3
),
array(
'title' => 'B',
'priority' => 2,
'sold_count' => 0
),
)
Step 3: Sort it by its priority (what I should get).
array(
array(
'title' => 'B',
'priority' => 2,
'sold_count' => 0
),
array(
'title' => 'C',
'priority' => 1,
'sold_count' => 3
),
array(
'title' => 'A',
'priority' => 0,
'sold_count' => 44
),
array(
'title' => 'D',
'priority' => 0,
'sold_count' => 33
),
)
Instead of getting what I want (step 3) I get an array with the priority sorted right however all other guides after have a random order. All guides that don't have a priority (priority === 0) should not be resorted.
I've tried a bunch of methods using asort, aasort, custom foreach and setting the key and this multisort (example below but taken from here and here, the example 3).
$sorterA =
$sorterB = array();
foreach($array as $k => $v) {
$sorterA[$k] = $k;
$sorterB[$k] = $v['priority'];
}
array_multisort($sorterA, SORT_NUMERIC, $sorterB, SORT_DESC, SORT_NUMERIC, $array);
Note: Both sorts need to be done separately (because the first sort isn't always sorted by sold_count but rather by date or other things).