php - Sort strings that also contain some integers -


using usort(), possible sort strings contain integer values?

for example, take 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 following code compares array elements simple string -

/** sort data (if sort key defined) */ if(!empty($_request['orderby'])) :     usort($emails, array(&$this, '_order_callback')); endif;  function _order_callback($item_a, $item_b){      /** grab 'orderby', must have been set function called */     $orderby = $_request['orderby'];      /** if no 'order' not set, default 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 usort  } 

the results delivered in following order -

[0] - 'test11@testing.com' [2] - 'test1@testing.com' [1] - 'test2@testing.com' 

where desire order -

[2] - 'test1@testing.com' [1] - 'test2@testing.com' [0] - 'test11@testing.com' 

is possible usort()? thanks.


edit

now know of existence of natsort() (thanks below comments/answers), able find , try -

$result = ($item_a[$orderby] > $item_b[$orderby] ? 1 : ($item_a[$orderby] < $item_b[$orderby] ? -1 : 0)); 

i added comparison _order_callback() function (if $orderby === email), , it's close, sorts in order 11, 12, 13, 14, 1, 2, 3, 4.

use strnatcmp() comparison in usort() callback

$email1 = new stdclass; $email1->email = 'test11@testing.com'; $email2 = new stdclass; $email2->email = 'test1@testing.com'; $email3 = new stdclass; $email3->email = 'test2@testing.com'; $email4 = new stdclass; $email4->email = 'test12@testing.com'; $email5 = new stdclass; $email5->email = 'test21@testing.com'; $email6 = new stdclass; $email6->email = 'test3@testing.com';  $invitees = array(     $email1,     $email2,     $email3,     $email4,     $email5,     $email6, );   usort($invitees, '_order_callback');  function _order_callback($item_a, $item_b){     return strnatcmp($item_a->email, $item_b->email); }  var_dump($invitees); 

Comments

Popular posts from this blog

matlab - Deleting rows with specific rules -

php - MySQLi multi_query results for later use -