Reputation: 1338
I have this Array,
Array
(
[0] => Array
(
[ID] => 108
[custom] => Array
(
[date_tps] => Array
(
[0] => 14.07.2014
)
)
)
[1] => Array
(
[ID] => 123
[custom] => Array
(
[date_tps] => Array
(
[0] => 22.07.2014
)
)
)
[2] => Array
(
[ID] => 152
[custom] => Array
(
[date_tps] => Array
(
[0] => 23.06.2014
)
)
)
[3] => Array
(
[ID] => 153
[custom] => Array
(
[date_tps] => Array
(
[0] => 06.07.2014
)
)
)
)
and I'm trying to sort it by date, date_tps[0]
field, from the new date to the old one.
can someone guide me how to make it done ?
I've tried using the php function to sort (those with $a-$b) but it didnt work (I guess its because its really inside many arrays.
thanks a lot!
Upvotes: 2
Views: 46
Reputation: 41873
Yes you need usort()
to this:
The simple hurdle is that you need to convert the times inside first before they are comparable.
$values = array(
array('ID' => 108, 'custom' => array('date_tps' => array('14.07.2014'))),
array('ID' => 123, 'custom' => array('date_tps' => array('22.07.2014'))),
array('ID' => 152, 'custom' => array('date_tps' => array('23.06.2014'))),
array('ID' => 108, 'custom' => array('date_tps' => array('06.07.2014'))),
);
usort($values, function($a, $b){
$v1 = $a['custom']['date_tps'][0];
$v2 = $b['custom']['date_tps'][0];
$v1 = DateTime::createFromFormat('d.m.Y', $v1); // convert them properly first
$v2 = DateTime::createFromFormat('d.m.Y', $v2);
return $v1->getTimestamp() - $v2->getTimestamp();
// or
return $v1->format('U') - $v2->format('U');
});
echo '<pre>';
print_r($values);
Upvotes: 1