Using usort()
, is it possible to sort strings that also contain integer values?
For example, take this array of objects containing email addresses (and other data) -
$invitees = Array(
[0] => Array(
'email' => 'test11@testing.com'
),
[1] => Array(
'email' => 'test2@testing.com'
),
[2] => Array(
'email' => 'test1@testing.com'
)
);
Using the following code compares the array elements as just a simple string -
/** Sort the data (if the sort key is defined) */
if(!empty($_REQUEST['orderby'])) :
usort($emails, array(&$this, '_order_callback'));
endif;
function _order_callback($item_a, $item_b){
/** Grab 'orderby', which must have been set for this function to be called */
$orderby = $_REQUEST['orderby'];
/** If no 'order' is not set, default to ASC */
$order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'ASC';
$result = strcmp($item_a[$orderby], $item_b[$orderby]);
return (strtoupper($order) === 'ASC') ? $result : -$result; //Send final sort direction to usort
}
The results are delivered in the following order -
[0] - 'test11@testing.com'
[2] - 'test1@testing.com'
[1] - 'test2@testing.com'
Where as I desire this order -
[2] - 'test1@testing.com'
[1] - 'test2@testing.com'
[0] - 'test11@testing.com'
Is this possible with usort()
? Thanks.
Edit
Now that I know of the existence of natsort()
(thanks to the below comments/answers), I was able to find and try this -
$result = ($item_a[$orderby] > $item_b[$orderby] ? 1 : ($item_a[$orderby] < $item_b[$orderby] ? -1 : 0));
I added that comparison to my _order_callback()
function (if $orderby === email
), and it's close, but sorts in the order 11, 12, 13, 14, 1, 2, 3, 4
.