I have a non-associative array where the data that comes in is not sorted (I'm receiving the data from an outside system and cannot force it to come into the array in sorted order.) Is there any way to sort the values? I've tried this:
$wedTrackTimes = array("9:30 AM-10:30 AM", "8:15 AM-9:15 AM", "12:30 PM-1:30 PM", "2:00 PM-3:00 PM", "3:30 PM-4:30 PM");
$wedTrackTimes = array_unique($wedTrackTimes);
$wedTrackTimes = sort($wedTrackTimes);
print_r($wedTrackTimes);
But instead of returning a sorted array, it returns 1. I'm assuming it's because it's non-associative, so there are no keys. Is there any way to sort an array by value only? We really need the 9:30 AM time slot to fall after the 8:15 AM slot, as it should.
UPDATE
Thanks to all for the answers; that did make the array sort, but not as expected. If I use the default sort type, I get this:
Array
(
[0] => 12:30 PM-1:30 PM
[1] => 2:00 PM-3:00 PM
[2] => 3:30 PM-4:30 PM
[3] => 8:15 AM-9:15 AM
[4] => 9:30 AM-10:30 AM
)
Using SORT_NUMERIC I get this:
Array
(
[0] => 2:00 PM-3:00 PM
[1] => 3:30 PM-4:30 PM
[2] => 8:15 AM-9:15 AM
[3] => 9:30 AM-10:30 AM
[4] => 12:30 PM-1:30 PM
)
Using SORT_STRING I get this:
Array
(
[0] => 12:30 PM-1:30 PM
[1] => 2:00 PM-3:00 PM
[2] => 3:30 PM-4:30 PM
[3] => 8:15 AM-9:15 AM
[4] => 9:30 AM-10:30 AM
)
What I need is:
Array
(
[0] => 8:15 AM-9:15 AM
[1] => 9:30 AM-10:30 AM
[2] => 12:30 PM-1:30 PM
[3] => 2:00 PM-3:00 PM
[4] => 3:30 PM-4:30 PM
)
Is this possible?
Sorting an array of objects in javascript is simple enough using the default sort() function for all arrays: const arr = [ { name: "Nina" }, { name: "Andre" }, { name: "Graham" } ]; const sortedArr = arr.
To sort an array of objects by date property: Call the sort() method on the array. Subtract the date in the second object from the date in the first. Return the result.
This give us access to all the methods of the Arrays class. We then created an array with numbers in a random order: int[] arr = { 5, 2, 1, 8, 10 }; . In order to sort this array in ascending order, we passed in the array as parameter to the sort() method: Arrays. sort(arr); .
So, it looks like you're looking for something a little more advanced than a standard sort.
// WARNING: THIS IS *NOT* BY REFERENCE. IT RETURNS A NEW ARRAY.
function getSortedTimes(array $group)
{
$tmp = array();
foreach( $group as $times )
{
// Basically, I am pairing the string for the start time with
// a numeric value.
$tmp[$times] = strtotime(substr($times, 0, strpos($times, '-')));
}
// asort is like sort, but it keeps the pairings just created.
asort($tmp);
// the keys of $tmp now refer to your original times.
return array_keys($tmp);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With