Carlos Salazar
Carlos Salazar

Reputation: 1898

How to sort an array by property value

I have an array that contains some string and a date,

[
    {
        date : '25-05-2018',
        string : 'foo'
    },
    {
        date : '15-01-2017,
        string : 'baz'
    },
    {
        date : '10-07-2018',
        string : 'bar'
    }
]

I need to sort the array based on the date field. Is there an efficient way to sort this array?

Notice: the array could have +250 rows, and they do not come from a database.

Upvotes: 2

Views: 38

Answers (1)

Felippe Duarte
Felippe Duarte

Reputation: 15131

Use usort to sort, parsing the date with DateTime

$json = '[
    {
        "date" : "25-05-2018",
        "string" : "foo"
    },
    {
        "date" : "15-01-2017",
        "string" : "baz"
    },
    {
        "date" : "10-07-2018",
        "string" : "bar"
    }
]';

$array = json_decode($json, true);

usort($array, function($a, $b) {
    $a = DateTime::createFromFormat('d-m-Y', $a['date']);
    $b = DateTime::createFromFormat('d-m-Y', $b['date']);
    return $a < $b; //change direction for asc/desc
});
var_dump($array);

Output

array (size=3)
  0 => 
    array (size=2)
    'date' => string '10-07-2018' (length=10)
    'string' => string 'bar' (length=3)
  1 => 
    array (size=2)
    'date' => string '25-05-2018' (length=10)
    'string' => string 'foo' (length=3)
  2 => 
    array (size=2)
    'date' => string '15-01-2017' (length=10)
    'string' => string 'baz' (length=3)

Upvotes: 1

Related Questions