php - Reordering 2D array by value -


$array = json_decode('[{"3609":1368486012},{"4286":1368546869},{"286":136848555}]',true); 

what efficient way reorder value decending (timestamp)?

reset returns value of first array element.

code:

$array = json_decode('[{"3609":1368486012},{"4286":1368546869},{"286":136848555}]',true);  usort($array, function($a, $b) {     return reset($b) - reset($a); });  var_dump($array); 

result:

array(3) {   [0]=>   array(1) {     [4286]=>     int(1368546869)   }   [1]=>   array(1) {     [3609]=>     int(1368486012)   }   [2]=>   array(1) {     [286]=>     int(136848555)   } } 

note: if use php 5.2 ,

$array = json_decode('[{"3609":1368486012},{"4286":1368546869},{"286":136848555}]',true);  function mysort($a, $b) {     return reset($b) - reset($a); } usort($array, 'mysort');  var_dump($array); 

oh, sorry
if compare float,

function mysort($a, $b) {     if ($a == $b)          return 0;     return ($a < $b) : 1 : -1; } 

or

function mysort($a, $b) {     return sprintf('%e', reset($b) - reset($a)); } 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -