This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 8 years ago.
I have an array that looks something like this:
Array
(
[0] => Array
(
[id] => 4
[date] => 15.12.2014
[archived] => 0
)
[1] => Array
(
[id] => 3
[date] => 19.12.2014
[archived] => 0
)
[2] => Array
(
[id] => 6
[date] => 15.11.2014
[archived] => 0
)
)
What I would like to do is sort the items into high-to-low order in the first dimension based on the date value in the second dimension. I can use strtotime() on the [date] field and produce a unix timestamp (please note, these dates are in Australian format and not US. The server produces the correct timestamp).
I'm aware that I can use arsort() to arrange this array, but I'm not sure how to do it based on the value of a second dimension array key.
I need the array to look like this:
Array
(
[0] => Array
(
[id] => 3
[date] => 19.12.2014
[archived] => 0
)
[1] => Array
(
[id] => 4
[date] => 15.12.2014
[archived] => 0
)
[2] => Array
(
[id] => 6
[date] => 15.11.2014
[archived] => 0
)
)
How can I best achieve this in PHP?
I've tried various arrangements of the following to no avail:
arsort($items, strtotime(['date']))
You should use usort
In your case:
usort($items, function($a, $b) {
return strtotime($a['date']) - strtotime($b['date']);
});
Suppose that your $array is declared that way:
$my_array = array(
array(
'id'=>4,
'date'=>'19.12.2014',
'archived'=>0),
array(
'id'=>3,
'date'=>'15.12.2014',
'archived'=>0),
array(
'id'=>6,
'date'=>'15.11.2014',
'archived'=>0));
You can use usort function with a closure function as follows
usort($my_array, function($a, $b) {
return strtotime($a['date']) - strtotime($b['date']);
});
usort will sort your array "in place", means that no copy of array will be returned but original array is sorted.
Moreover, I've used strtotime to make order between dates as a starting dates are represent as strings and not in "real date" format.
Moreover keep in mind that
Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than
just reordering the keys.
Execution test
Array
(
[0] => Array
(
[id] => 6
[date] => 15.11.2014
[archived] => 0
)
[1] => Array
(
[id] => 4
[date] => 15.12.2014
[archived] => 0
)
[2] => Array
(
[id] => 3
[date] => 19.12.2014
[archived] => 0
)
)
Related
I have an array like this, i need to get the unique associative index
Array
(
[0] => Array
(
[id] => 200
[name] => james
[place] => ca
)
[1] => Array
(
[id] => 201
[name] => jana
[place] => uk
)
[2] => Array
(
[id] => 203
[name] => jana
[place] => ca
)
)
That means i need to get the unique 'place' from that array like
ca,uk
Make use of array_column() and array_unique()
array_unique(array_column($array, 'place'))
array_column — Return the values from a single column in the input
array (PHP 5 >= 5.5.0, PHP 7)
array_unique — Removes duplicate values from an array (PHP 4 >= 4.0.1, PHP 5, PHP 7)
This question already has answers here:
How do I Sort a Multidimensional Array in PHP [duplicate]
(10 answers)
Closed 7 years ago.
I want to sort this array on basis of 'eta'.Lowest eta must come to first.
My array is :
Array
(
[0] => Array
(
[company] => Uber
[type] => Saloon
[eta] => 8
[destination_required] => N
[reject_booking_request] => N
)
[1] => Array
(
[company] => greentomato
[type] => Saloon
[company_rating] => 80%
[eta] => 10
[destination_required] => N
[reject_booking_request] => N
)
[2] => Array
(
[company] => CATALINA
[type] => Exec
[eta] => 12
[destination_required] => Y
[reject_booking_request] => N
)
[3] => Array
(
[company] => Uber
[type] => Exec
[eta] => 15
[destination_required] => N
[reject_booking_request] => N
)
[4] => Array
(
[company] => Hailo
[type] => Taxi
[eta] => 1
[destination_required] => Y
[reject_booking_request] => Y
)
)
I want to sort this array on basis of 'eta'.Lowest eta must come to first.
I tried to use this :
$result = Set::sort($array, '{n}', 'asc');
But it gives some error.
You can use usort:
usort($yourArray, function($a, $b) {
return $a['eta'] - $b['eta'];
});
Usort allows the definition of a custom sortation callback function as the second parameter. Inside the body of this method you can define your comparison algorithm.
If the method returns a negative number it will move the $b variable down the array, returning a positive number will move $b up the array and return 0 keeps $b in the same place.
We have defined an inline callback method for simplicity sake.
I did that in cakephp :
My Ans is :
Hash::sort($array, '{n}.eta', 'asc');
You can use array multisort function.
Follow the link for more information.
http://php.net/manual/en/function.array-multisort.php
hello i am learning PHP and came upon this multi-level array after using print_r on $this->root
Array (
[0] => 9
[obj] => 3562
[gen] => 0
[1] => Array (
[0] => 5
[1] => Array (
[/AcroForm] => Array (
[0] => 8
[1] => 3563
[2] => 0
)
[/Metadata] => Array (
[0] => 8
[1] => 3559
[2] => 0
)
[/PageLabels] => Array (
[0] => 8
[1] => 3389
[2] => 0
)
[/Pages] => Array (
[0] => 8
[1] => 3392
[2] => 0
)
[/Type] => Array (
[0] => 2
[1] => /Catalog
)
)
)
) Array (
[0] => 9
[obj] => 8
[gen] => 0
[1] => Array (
[0] => 5
[1] => Array (
[/Type] => Array (
[0] => 2
[1] => /Catalog
)
[/Pages] => Array (
[0] => 8
[1] => 1
[2] => 0
)
[/OpenAction] => Array (
[0] => 6
[1] => Array (
[0] => Array (
[0] => 8
[1] => 3
[2] => 0
)
[1] => Array (
[0] => 2
[1] => /FitH
)
[2] => Array (
[0] => 0
)
)
)
[/PageLayout] => Array (
[0] => 2
[1] => /OneColumn
)
)
)
)
i have an question about the behavior of using multi-level arrays, i want to use this function
$pages = $this->pdf_resolve_object($this->c, $this->root[1][1]['/Pages']);
and $this->root[1][1]['/Pages'] which i believe is used to check the array for these keys and if it exists then use as variable for pdf_resolve_object
so my question is 2-fold, one is does $this->root[1][1]['/Pages'] check the array and goes through the keys? if not what is its behavior? and 2 when it checks the array does it go through just the top 4 keys or all of the sub-keys?
If someone can help or link me to some learning material that would be much appreciated, thank you!
1) It does not check for the presence of the array keys -- rather it assumes that those keys already exist and passes the value into the function. If any of the keys did not exist, PHP would issue an E_NOTICE to the effect of Notice: Undefined index: that the key was not found. To check for them would require a call to isset() or array_key_exists() like:
if (isset($this->root[1][1]['/Pages'])) {
$pages = $this->pdf_resolve_object($this->c, $this->root[1][1]['/Pages']);
}
2) There is no need for it to iterate through to find the keys. Knowing the array keys already means they can be accessed directly without iteration. In memory, PHP has stored the array keys and the memory locations of the values they point to. Therefore, with the key alone, PHP can return the value without needing to traverse the array.
There is a lot of good information in the PHP manaul on Arrays
iam trying to sort this array by array[key]['premium']['Monthly'] and if there are two Monthly prices the same, then sort by quarterly, then semi-annual, then annual.
i search and couldnt figure out how to use array_multisort function.
Array (
[0] => Array (
[product_id] => 1
[rate] => 27.07
[premium] => Array (
[Annual] => 436.05
[Semi-Annual] => 226.75
[Quarterly] => 115.6
[Monthly] => 37.11
)
)
[1] => Array (
[product_id] => 2
[rate] => 35.00
[premium] => Array (
[Annual] => 565
[Semi-Annual] => 293.8
[Quarterly] => 149.73
[Monthly] => 50.85
)
)
[2] => Array (
[product_id] => 3
[rate] => 30.52
[premium] => Array (
[Annual] => 497.8
[Monthly] => 47.29
)
)
)
I think you want to use usort function, something like
function compare($a, $b){
$p1 = $a["premium"];
$p2 = $b["premium"];
if($p1["Monthly"] == $p2["Monthly"]){
// compare by quarterly
...
}else{
if($p1["Monthly"] < $p2["Monthly"])then return -1;
else return 1;
}
}
usort($prices, "compare");
where $prices is your array. The comparision function isn't implemented fully, just to show the idea. Also, since it looks like there might be missing items in the price array (ie last one misses Quarterly and Semi-Annual) you have to check first (before comparison) does the items exists and take appropriate action in case one or both are missing.
I want to make it so that my multi dimensional array is in a random order. How would you do it?
// This is how the array looks like
print_r($slides);
Array
(
[0] => Array
(
[id] => 7
[status] => 1
[sortorder] => 0
[title] => Pants
)
[1] => Array
(
[id] => 8
[status] => 1
[sortorder] => 0
[title] => Jewels
)
[2] => Array
(
[id] => 9
[status] => 1
[sortorder] => 0
[title] => Birdhouse
)
[3] => Array
(
[id] => 10
[status] => 1
[sortorder] => 0
[title] => Shirt
)
[4] => Array
(
[id] => 11
[status] => 1
[sortorder] => 0
[title] => Phone
)
)
// This how the result is if I use array_rand()
print_r(array_rand($slides, 5));
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
)
// This how the result is if I use shuffle()
print_r(shuffle($slides));
1
shuffle() is the way to go here. It prints 1 because shuffle changes the array in-place and returns a boolean, as it is written in the documentation:
Returns TRUE on success or FALSE on failure.
I suggest to also read the documentation of array_rand():
Picks one or more random entries out of an array, and returns the key (or keys) of the random entries.
Always read documentation if you use built-in functions. Don't just assume how the work. I bet it took more time to write the question than looking this up.
Instead of
print_r(shuffle($slides));
do
shuffle($slides);
print_r($slides);
You see shuffle() shuffles the array in-place
i am not sure how you want it to display but you can loop the array and use php rand(0,arraylen) function to parse the array.
It works perfect. print_r(shuffle($slides))) gives the output of TRUE, since the return value of shuffle is a boolean and not an array.
See the working example here: http://codepad.org/B5SlcjGf