Skip to content
Advertisement

Order Array of objects by two fields , date and order

i need order and array of objects by two fields :

1- date, closests to today

2- order (10 maximun and 0 minimun) ASC

i use usort for order by date :

usort($array, function($a, $b) {
    return ( (abs(strtotime("now") - strtotime($a->date)) - (abs(strtotime("now") - strtotime($b->date)))) );
});

but i can’t with the field order ASC any idea please ?

Advertisement

Answer

$array = [
  (object)["date" => "+2 minutes","order" =>  2],
  (object)["date" => "+2 minutes","order" =>  1],
  (object)["date" => "+1 minutes","order" =>  2],
];

usort($array, function($a, $b) {
        $v1 =  abs(strtotime("now") - strtotime($a->date)) <=> abs(strtotime("now") - strtotime($b->date));
        return $v1 ? $v1 : ($a->order <=> $b->order);
    });

echo "<pre>";
var_export($array);

Output:

array (
  0 => 
  (object) array(
     'date' => '+1 minutes',
     'order' => 2,
  ),
  1 => 
  (object) array(
     'date' => '+2 minutes',
     'order' => 1,
  ),
  2 => 
  (object) array(
     'date' => '+2 minutes',
     'order' => 2,
  ),
) 
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement