I'm having trouble getting usort to work and not sure what I'm missing. Below is an example of my array. I want to sort the array based on the value of the sort key.
Array
(
[0] => Array
(
[sort] => 1520546956
[row] => Data lives here
)
[1] => Array
(
[sort] => 1521047928
[row] => Data lives here
)
[2] => Array
(
[sort] => 1520525366
[row] => Data lives here
)
[3] => Array
(
[sort] => 1520525227
[row] => Data lives here
)
My code to try and sort this is:
foreach ($resultsArray as $record)
{
usort($record['sort'], function($a, $b)
{
if ($a == $b)
{
return 0;
}
return ($a < $b) ? -1 : 1;
});
}
However my code seems to be ineffective as the order of the array isn't changing. I feel like I'm close but can't identify what I'm missing. Thank you for any help!
$recordwill be a copy of the array element, not a reference. Thus, any changes you make to the element will not persist. To fix this, either doforeach($resultsArray as $index=>$record)and then$resultsArray[$index] = $recordafter sorting, or doforeach($resultsArray as &$record)--note the&in this second example!usortsorts the given array in place. Thus,$record['sort']should be an array. If you want to useusortproperly, dousort($resultsArray, function($a, $b) { /* compare $a['sort'] and $b['sort'] */ }! This will completely avoid the need for aforeachloop.usort($resultsArray, function($a, $b) { /* compare $a['sort'] and $b['sort'] */ }and working correctly now. Thank you!