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.
Related
I need an array sorted by Unix timestamp values. I attempted to use both ksort and krsort before realising that occasionally the timestamp values might be the same (and you cannot have duplicate keys in arrays).
Here's an example array I may be faced with:
$array = array(
[
"unix" => 1556547761, // notice the two duplicate unix values
"random" => 4
],
[
"unix" => 1556547761,
"random" => 2
],
[
"unix" => 1556547769,
"random" => 5
],
[
"unix" => 1556547765, // this should be in the 3rd position
"random" => 9
]
);
So what I'm trying to do is sort them all based on each child arrays unix value, however I cannot figure out how to do so. I have tried countless insane ways (including all other sort functions and many, many for loops) to figure it out - but to no avail.
All help is appreciated.
You can use usort which sort your array by given function
Define function as:
function cmpByUnix($a, $b) {
return $a["unix"] - $b["unix"];
}
And use with: usort($array, "cmpByUnix");
Live example: 3v4l
Notice you can also use asort($array); but this will compare also the "random" field and keep the key - if this what you need then look at Mangesh answer
array_multisort() — Sort multiple or multi-dimensional arrays
array_columns() — Return the values from a single column in the input array
You can use array_multisort() and array_column(), then provide your desired sort order (SORT_ASC or SORT_DESC).
array_multisort(array_column($array, "unix"), SORT_ASC, $array);
Explanation:
In array_multisort(), arrays are sorted by the first array given. You can see we are using array_column($array, "unix"), which means that the second parameter is the order of sorting (ascending or descending) and the third parameter is the original array.
This is the result of array_column($array, "unix"):
Array(
[0] => 1556547761
[1] => 1556547761
[2] => 1556547765
[3] => 1556547769
)
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.
Note:If two members compare as equal, their relative order in the sorted array is undefined.
Refer : https://www.php.net/manual/en/function.asort.php
asort($array);
echo "<pre>";
print_r($array);
echo "</pre>";
It will give you the output as
Array
(
[1] => Array
(
[unix] => 1556547761
[random] => 2
)
[0] => Array
(
[unix] => 1556547761
[random] => 4
)
[3] => Array
(
[unix] => 1556547765
[random] => 9
)
[2] => Array
(
[unix] => 1556547769
[random] => 5
)
)
You can keep the array key [1],[0],[3],[2]) as it is Or you can keep it as sequential as per your requirement.
I have a array named $itemIds and it consists of the following datas. The key is the items id and the value is the date time that can be converted to a readable date.What I want to do is simply sort the order of the array according to the value (time). I'm totally new to php and some examples or tips would be great ! I would love to hear from you.
Array
(
[10477] => 1508898726
[10549] => 1508898744
[10891] => 1508898752
)
If I use this code I get the following data from the print_r.
if (isset($itemIds)) {
$time = array();
foreach ($itemIds as $key => $val) {
print_r($key.'=>'.date('m/d/Y H:i:s', $val));
}
}
The problem starts from here.I want to sort(asc & desc) the $itemsIds according to the date time.
10477 => 10/25/2017 11:32:06
10549 => 10/25/2017 11:32:24
10891 => 10/25/2017 11:32:32
I want to sort the data then use array_keys($shopIds) to change it like the following data
Array
(
[0] => 10477
[1] => 10549
[2] => 10891
)
I think the easier approach would be to sort the data and then flip it so the keys are values. If you look at your data you are initially dealing with actual timestamps from what I can see. Use them, don't change them to strings. I say this because you are just causing yourself to do extra work without any reason and introducing a layer of complexity that is not needed. Instead I would do the following:
$array = [
10477 => 1508898726,
10549 => 1508898744,
10891 => 1508898752,
];
arsort($array);
$sorted_array = array_values(array_flip($array));
This is easy to read and does not involve the extra function. The result you are left with is:
Array
(
[0] => 10477
[1] => 10549
[2] => 10891
)
A little explanation:
I am using arsort() or asort() (based on the direction you want to sort) in order to sort based on the values in the array.
Then I use array_flip() on the array in order to swap the keys and values.
And last I am using array_keys() to reset the indexes in the array and maintain its sort.
Hope this helps!
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)
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']);
});