4

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

shatheesh
  • 633
  • 6
  • 10
user3754680
  • 73
  • 1
  • 1
  • 6
  • Start from here: http://www.php.net/manual/en/ref.array.php – hindmost Jun 19 '14 at 12:06
  • 1
    Since you haven't made an effort to solve the problem yourself, it seems that you are looking to [hire a paid freelancer to fix the problem for you](http://www.freelancer.com). – h2ooooooo Jun 19 '14 at 12:07
  • you answer is here http://stackoverflow.com/questions/2910611/php-sort-a-multidimensional-array-by-element-containing-date – Ashouri Jun 19 '14 at 12:11
  • you answer is here http://stackoverflow.com/questions/2910611/php-sort-a-multidimensional-array-by-element-containing-date – Ashouri Jun 19 '14 at 12:12

1 Answers1

14

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!
Matteo Tassinari
  • 18,121
  • 8
  • 60
  • 81
  • will it be sort by time? and i used array_slice($array, 0, 3); as well but when i printed my list my keys were replaced with 0,1,2 – user3754680 Jun 19 '14 at 12:09
  • @user3754680 [Read. The. Manual](http://us2.php.net//manual/en/function.array-slice.php). The last parameter. – h2ooooooo Jun 19 '14 at 12:10