Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP slice associative array [closed]

Tags:

arrays

php

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

like image 809
user3754680 Avatar asked Dec 12 '22 05:12

user3754680


1 Answers

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!
like image 62
Matteo Tassinari Avatar answered Dec 28 '22 01:12

Matteo Tassinari