I have an array in this format:
Array
(
[0] => Array
(
[28th February, 2009] => 'bla'
)
[1] => Array
(
[19th March, 2009] => 'bla'
)
[2] => Array
(
[5th April, 2009] => 'bla'
)
[3] => Array
(
[19th April, 2009] => 'bla'
)
[4] => Array
(
[2nd May, 2009] => 'bla'
)
)
I want to sort them out in the ascending order of the dates (based on the month, day, and year). What's the best way to do that?
Originally the emails are being fetched in the MySQL date format, so its possible for me to get the array in this state:
Array
[
['2008-02-28']='some text',
['2008-03-06']='some text'
]
Perhaps when its in this format, I can loop through them, remove all the '-' (hyphen) marks so they are left as integars, sort them using array_sort() and loop through them yet again to sort them? Would prefer if there was another way as I'd be doing 3 loops with this per user.
Thanks.
Edit: I could also do this:
$array[$index]=array('human'=>'28 Feb, 2009',
'db'=>'20080228',
'description'=>'Some text here');
But using this, would there be any way to sort the array based on the 'db' element alone?
Edit 2: Updated initial var_dump
Use the ISO (yyyy-mm-dd) format rather than the "english" format, and then just use the ksort function to get them in the right order.
There's no need to remove the hyphens, ksort will do an alphanumeric comparison on the string keys, and the yyyy-mm-dd format works perfectly well as the lexical order is the same as the actual date order.
EDIT I see you've now corrected your question to show that you've actually got an array of arrays, and that the sort key is in the sub-arrays. In this case, you should use uksort as recommended elsewhere, but I would recommend that you go with your own edit and sort based on the DB formatted date, rather than by parsing the human readable format:
function cmp($a, $b)
{
global $array;
return strcmp($array[$a]['db'], $array[$b]['db']);
}
uksort($array, 'cmp');
Actually, use this:
usort($array, "cmp");
function cmp($a, $b){
return strcmp($b['db'], $a['db']);
}
:)
function cmp($a, $b) {
global $array;
return strcmp($array[$a]['db'], $array[$b]['db']);
}
uksort($array, 'cmp');
I think there is better to use usort() function instead of uksort(), because sometimes you can`t use global variables at all and anyway using global variables is not a good practice either.
You could also use an anonymous function.
// Sort in chronological order.
usort($array, function($a, $b) {
return strcmp($a['db'], $b['db']);
});
Related
I have an array that looks like this:
( [0] => 03-11-2013 [1] => 04-09-2016 )
How do I order it so that the greatest date always comes first?
Thanks
Here's one:
array_multisort(array_map('strtotime', $array), SORT_DESC, $array);
Convert to timestamps and sort descending, sorting the original array. Might be better to have them as timestamps or YYYY-MM-DD if you control the array creation.
I have an array of timestamps that look like this:
2012-11-19 19:45
I need to sort them by date. I could do a bubble sort or something if i could get the unix timestamp of a date, but i don't know what function gives me that. I looked at strtotime but it won't let me pass a date format. I'm also not sure a bubble sort is the best way to go.
Any suggestions?
Array example:
Also, sorry, i should have mentioned it was in 'show_date'.
Array
(
[15] => Array
(
[show_date] => 2012-11-19 10:40
)
[16] => Array
(
[show_date] => 2012-11-20 10:40
)
[17] => Array
(
[show_date] => 2012-11-21 10:40
)
[18] => Array
(
[show_date] => 2012-11-22 10:40
)
)
No need to overcomplicate this. Just use the built-in sort function:
sort($timestamp_array);
You don't need to convert to UNIX timestamps because the strings are in the standard "ISO sortable date" format. That means that if you sort the strings, the dates will be in the correct order.
Here is a php -a session that shows how it works:
php > $ts = array('1986-01-31 12:11', '2012-01-01 13:12', '1980-10-10 12:00');
php > sort($ts);
php > echo var_export($ts);
array (
0 => '1980-10-10 12:00',
1 => '1986-01-31 12:11',
2 => '2012-01-01 13:12',
)
You can just sort it with PHP standard sort. See Sorting Arrays
asort($timestamps);
For your example, you can define a comparison function
function cmp_show_date($a, $b)
{
if ($a['show_date'] == $b['show_date']) {
return 0;
}
return ($a['show_date'] < $b['show_date']) ? -1 : 1;
}
and use that in usort
usort($timestamps, 'cmp_show_date');
You could use a combination of usort() and strtotime, but I'd rather use the DateTime class and its getTimestamp method because it can handle time zones and several formats.
You do not need date format to pass that particular date. When you pass strtotime('2012-11-19 19:45'); it will return UNIX time stamp.
EDIT:
$arr = array();
foreach ($dates as $k => $v) {
$arr[$k] = strtotime($v['date']);//or $k if your date is the index
}
array_multisort($arr, SORT_ASC, $dates);
Even though I have read the PHP documentation and this looks like to be a FAQ, it's still giving me some headache.
I have an array like this which holds the months of the year:
[12] => december
[4] => april
[3] => march
[6] => june
[7] => july
[10] => october
...and so on
The order is not as it should be. I want to reorder the keys numerically. I can swap the keys with values if I want, but while each numerical value will match the corresponding month, they will never be in order. So I thought of putting these in order via PHP.
I have tried with $calendar = ksort( $myarray );
But If I try to print $calendar, I will only get bool=true or array with a single key and "1" as value... I was planning to use the ksort result in a foreach later, but I can't.
What I'm droing wrong?
No .. just use:
ksort($myarray);
print_r($myarray)
Codepad example
ksort() sorts an array by key, maintaining key to data correlations, returns TRUE on success or FALSE on failure, if you associate the $calendar with ksort() you will have what ksort returns.
ksort($arr);
foreach ($arr as $key => $val)
{
echo "$key = $val\n";
}
I'm trying to sort this array by the date but the array is merged and has two different types of date.
[0] => Object
[Something] => hey
[date]=>2010-01-03
[1] => Object
[something] => heyagain
[somethingelse] => heythere
[posted_date] => 2011-08-22
I want this array to sort the whole array by date and posted date but the array comes out in order as:
Array1=>(date1,date2,date3) Array2=>(date1,date2,date3)
For instance in (Array2,date2) may be before (Array1,date1) but it does not sort that way. I want to see
Output=>Array2(date1),Array2(date2),Array1(date1),Array2(date3),Array1(date2),Array1(date3
I have tried array_multisort($merge, SORT_NUMERIC, $arg, 'posted_date', SORT_DESC, 'date', SORT_DESC) and a few other but I can't get it to work. I hope this isn't confusing anyone.
To use array_multisort, you need to create multiple arrays first, e.g. accessing properties that you want to sort over and wrapping those into another array.
The manual page gives good examples how to do this or that. However strings just won't work:
array_multisort($merge, SORT_NUMERIC, $arg, 'posted_date', SORT_DESC, 'date', SORT_DESC);
See as well: Sort data of Php array by values of another array
I have an array of products
$products = array_count_values($products);
now I have an array where $key is product number and $value is how many
times I have such a product in the array.
I want to sort this new array that product with the least "duplicates" are
on the first place, but what ever I use (rsort, krsort,..) i loose product
numbers (key).
any suggestions?
thanks.
Take a look at arsort() as an alternative to rsort() (and that family of functions).
Generally, the 'Sorting arrays' page on php.net might be useful to you - it's a comparison of PHP's array sorting functions based on what they sort, what direction they sort in, and whether they maintain the keys while sorting.
Mind you, for the sake of completion:
Going by 'now I have an array where $key is product number and $value is how many times I have such a product in the array. I want to sort this new array that product with the least "duplicates" are on the first place', you probably want asort() (the pendant to sort()).
Your comment example, using asort():
$arr = array(
1 => 3,
2 => 2,
5 => 3,
9 => 1
);
asort($arr);
print_r($arr);
yields:
Array
(
[9] => 1
[2] => 2
[1] => 3
[5] => 3
)
You want to use asort():
This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.
rsort() was wrong from the first place anyway (and so are any other sorting functions that have the r (for reverse) in it), as it would sort the array from highest to lowest.
asort() sorts from lowest to highest:
<?php
$array = array('f'=>1, 'a'=>2, 'c'=>5);
asort($array);
print_r($array);
gives
Array
(
[f] => 1
[a] => 2
[c] => 5
)
Note: These functions sort the arrays in-place. They do not return a sorted array. The return values is:
(..) TRUE on success or FALSE on failure.
Try using asort() or arsort() or any other sort function that maintains index association.
You should use asort() PHP function.
asort() is array sort, not ascending sort.
dsort doesn't exist. The function you are looking for is arsort() - array reverse sort.
https://www.php.net/manual/en/function.asort.php
https://www.php.net/manual/en/function.arsort.php
Just a thought;
asort - sorts ascending (low to high)
perhaps try
dsort - descending (high to low)