2

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.

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.