PHP slice associative array

user3754680

This is my array

$array = array(
    "13111" => "2014-06-21 19:51:00.0000000",
    "23111" => "2014-06-20 19:51:00.0000000",
    "12111" => "2014-06-21 19:51:00.0000000",
    "23311" => "2014-06-22 19:51:00.0000000",
    "13114" => "2014-06-21 19:51:00.0000000",
    "23711" => "2014-06-20 19:51:00.0000000",
);

How can i get first 3 elements of my array and how can i sort by datetime? thanks

Matteo Tassinari

What you want is:

sort($array);
$array = array_slice($array, 0, 3);

first, the sort function will sort them lexicographically (which in this case coincides with the date) and then you slice it to get the elements you want.

EDIT

If you want to preserve the keys just use

asort($array); // "asort" instead of simple "sort"
$array = array_slice($array, 0, 3, true); // note the final "true" parameter!

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related