1

I created this code to reference a Json array and built a list:

<?php

    $json = file_get_contents('events.json');

    $jsonArray = json_decode($json, true); // decode the JSON into an associative array

    foreach ($jsonArray as $value) {

        if (($value['active'] === 't') && ($value['fromDate'] >= $currentDate)) {

            echo '<p>'.$value['title'].' '.$value['fromDate'].' - '.$value['toDate'].'</p>';
        }
    }

    echo $currentDate;  
?>

However, I can't figure out how to organize by a value in the Json file:

[
    {

        "active": "f",
        "title": "My Third Event",
        "city": "Robert Downey Jr.",
        "ST": "Robert Downey Jr.",
        "fromDate": "01/17",
        "toDate": "01/20",
        "website": "http://google.com",
        "email": "[email protected]",
        "logo": ""
    },
    {

        "active": "t",
        "title": "My First Event",
        "city": "Robert Downey Jr.",
        "ST": "Robert Downey Jr.",
        "fromDate": "05/12",
        "toDate": "01/20",
        "website": "http://google.com",
        "email": "[email protected]",
        "logo": ""
    }
]

I want to use "fromDate" to dynamically organize each entry when loaded. Any advise? FYI - i have reviewed the PHP manual and other SO entries, but i'm new to PHP and Ive not got my head totally wrapped around the concepts just yet. Thanks!

2
  • So you want to order your array by the key toDate ?! Commented Apr 10, 2015 at 21:23
  • Yes. order each entry by fromDate... not toDate. Commented Apr 10, 2015 at 21:35

1 Answer 1

1

This should work for you:

Here I just sort your array with usort() by comparing the timestamps of the "fromDate".

usort($jsonArray, function($a, $b) {
    if(strtotime($a["fromDate"]) == strtotime($b["fromDate"]))
        return 0;
    return strtotime($a["fromDate"]) > strtotime($b["fromDate"])? 1: -1;
});
Sign up to request clarification or add additional context in comments.

2 Comments

Guiness! that worked. However I may need to dynamically get the year as it will eventually change.
@trobbins26 You're welcome! See my updated answer, forgot that strtotime() just takes the current year if you don't add one, so it should all works fine

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.