I'm trying to multisort a DB array based on the users status. Those with Status = 1 go at the top, those with Status = 0 go at the bottom of the array. I thought I had it working but it just stopped today with the addition of new rows to the DB.
uasort($ven, function ($a, $b) { return $a['v_status'] == '1' ? false : true; });
It's a simple DB array from MySQL:
Array (
[0] => array(
[name] => '',
[v_status] => 0
[1] => array(
[name] => '',
[v_status] => 1
)
As mentioned in comments to my other answer, splitting the array into active/inactive arrays could be a better solution than sorting.
$items = array(
array('name' => 'active1', 'active' => '1'),
array('name' => 'inactive1', 'active' => '0'),
array('name' => 'active2', 'active' => '1'),
array('name' => 'inactive2', 'active' => '0'),
array('name' => 'inactive3', 'active' => '0'),
array('name' => 'active3', 'active' => '1'),
array('name' => 'inactive4', 'active' => '0'),
);
$active = array_filter($items, function($item){ return $item['active'] == '1'; });
echo '<pre>' . print_r($active,true);
// You could filter again here, not sure which would be quicker,
// but my guess would be the array_diff method (which also ensures
// that no items get filtered out by both filters)
$inactive = array_diff_key($items, $active);
echo '<pre>' . print_r($inactive,true);
uasort expects the callback to return a positive integer if $a should be above $b, a negative integer if $b should be above $a or 0 if they are equal.
This is why despite there only being 2 options Jon's suggestion return $b['v_status'] - $a['v_status'];
is correct.
In your case if at some point during the sort $a[v_status] = 0 and $b[v_status] = 1 the function looks at $a[v_status], returns false, which equates to 0 and the algorithm (quick sort I think) treats them as equal and therefore leaves them in their current order.
See PHP: usort for reference, which expects a similar callback.