$result = array("test" => "21:00", "test" => "11:00", "test" => "19:00", "test" => "04:00");
$sortedArray = array();
foreach ($result as $test => $mealTime) {
if () {
array_push($sortedArray, $mealTime);
}
}
This is what I have done right now. I would like to make a new array out of the $result array. And in this new array I would like it to be sorted out from the meal times.
As you see in the current $result array it is unsorted as 04:00 which is in the end of the array is lower than 21:00.
So the correct array would be: 04:00, 11:00, 19:00, 21:00 (in the above example).
How can I do this? The above code is just an example of what I tried and then got stuck at writing a if statement to it..
First of all: do you really need an index as a string? You always use “test”? Is this just an example?
If you don’t need it, simply do this:
One dimensional array
Output:
Using a multi-dimensional array
(based on the code you provided in the comment)
This sample does what you want but it’s not the way I would do it. I recommend using a class instead a second array. This is much cleaner and uses a more advanced coding style. As far as I see from your example your are creating the arrays manually so it does not result in a big change.
Output:
Otherwise you can use sort(), asort() as Liam Allan suggested or uasort().
Check Sorting Arrays for a comparison of these functions to find out the one that best fits your needs.