1

I the folder data i store json files which look like this:

{
    "date": "2021-08-05",
    "time": "13:00",
    "name": "John"
}

To loop through all the json files:

$files = glob('data/*.json'); // all json files in data dir
foreach($files as $file) {
   $objs = json_decode(file_get_contents($file)); // all json objects in array
   echo $objs->date.'<br />';
}

Output above gives me all dates but in ascending order. How can i output them in descending order? (oldest date first)

1
  • 5
    Put all the data into a single array and then sort it, before outputting Commented Aug 8, 2021 at 15:14

1 Answer 1

2

You can try this way with pushing all the individual array's to a single array and the use array_multisort like below to sort by date field,

$files = glob('data/*.json'); // all json files in data dir
foreach($files as $file) {
   $main[] = json_decode(file_get_contents($file),1); // push individual array
}
array_multisort(array_column($main, 'date'), SORT_DESC, $main);
print_r($main);
Sign up to request clarification or add additional context in comments.

2 Comments

Ok. But how does my foreach now look like to create the output?
The same way I added above, it just uses the foreach and pushes the individual $file as an array to the new array $main. Some kind of demo for clarity: rextester.com/FMBBVR78628

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.