Array sorting by key value in php [duplicate] - php

This question already has answers here:
How to Sort a Multi-dimensional Array by Value
(16 answers)
Closed 2 years ago.
I would like to sort below array based on amount but I don't know how. Anyone help me
Array(
[0] => Array
(
[id] => 1
[amount] => 20
)
[1] => Array
(
[id] => 2
[amount] => 30
)
[2] => Array
(
[id] => 3
[amount] => 10
)
)

Something like
PHP7+
usort($array, function($a, $b){
return $a['amount'] <=> $b['amount'];
});
What is <=> (the 'Spaceship' Operator) in PHP 7?
< PHP 7
usort($array, function($a, $b){
if( $a['amount'] == $b['amount'] )
return 0;
else if($a['amount'] > $b['amount'])
return 1;
else
return -1
});
OR you can just subtract them like everyone else...

usort [1] will do the job using a custom comparator function which indexes into the amount property and performs a standard integer comparison for less than/greater than. Sort descending with $b["amount"] - $a["amount"] if you wish.
$data = [
[
"id" => 1,
"amount" => 20
],
[
"id" => 2,
"amount" => 30,
],
[
"id" => 3,
"amount" => 10
]
];
usort($data, function ($a, $b) {
return $a["amount"] - $b["amount"];
});
print_r($data);
Output:
Array
(
[0] => Array
(
[id] => 3
[amount] => 10
)
[1] => Array
(
[id] => 1
[amount] => 20
)
[2] => Array
(
[id] => 2
[amount] => 30
)
)

Use usort.
E.g
function sortByAmount($x, $y) {
return $x['amount'] - $y['amount'];
}
usort($array, 'sortByAmount');
echo "<pre>"; print_r($array);

Use usort function like this (know more about usort click here):
$array = array(array('id'=>1,'amount'=>20),array('id'=>2,'amount'=>30),array('id'=>3,'amount'=>10));
Create custom function like this:
function sortByAmount($x,$y){
return $x['amount']-$y['amount'];
}
Then use usort function like this:
usort($array,'sortByAmount');
// then print
echo"<pre>"; print_r($array);

Related

usort function result is wrong

Today I provided the answer of this question and I wrote a script, but I found out that something went wrong.
Here is the first script
<?php
$array = array(
"0" => array (
"id" => 1204,
"custom_price" => 33.1500
),
"1" => array (
"id" => 1199,
"custom_price" => 15.83
),
"2" => array (
"id" => 1176,
"custom_price" => 16.83
)
);
usort($array, function($a, $b) {
return $a['custom_price'] - $b['custom_price'];
});
echo "<pre>";
print_r($array);
and its output is (also you can check output on sandbox)
<pre>Array
(
[0] => Array
(
[id] => 1176
[custom_price] => 16.83
)
[1] => Array
(
[id] => 1199
[custom_price] => 15.83
)
[2] => Array
(
[id] => 1204
[custom_price] => 33.15
)
)
So, my desired output should be sort like (custom_price 15.83, 16.83, 33.15000) but the actual output is (custom_price 16.83,15.83,33.15000). you can see 15.83 is smallest from 16.83. the sorting result is wrong
So, when I change custom_price 15.83 to 14.83 then sorting output is correct
<pre>Array
(
[0] => Array
(
[id] => 1199
[custom_price] => 14.83
)
[1] => Array
(
[id] => 1176
[custom_price] => 16.83
)
[2] => Array
(
[id] => 1204
[custom_price] => 33.15
)
)
you can see output on sandbox
I can't understand what's going on.. any idea about this ?
My Question is: I check each iteration but can't identify the problem. when custom_price is 15.83 then result is wrong. why?
There is a warning in the PHP manual about the return values from the usort() compare function (at http://php.net/manual/en/function.usort.php#refsect1-function.usort-parameters)...
Caution Returning non-integer values from the comparison function,
such as float, will result in an internal cast to integer of the
callback's return value. So values such as 0.99 and 0.1 will both be
cast to an integer value of 0, which will compare such values as
equal.
Also from PHP 7. you can use the spaceship operator <=> which returns 1, 0, -1 depending on the comparison of the two values...
usort($array, function($a, $b) {
return $a['custom_price'] <=> $b['custom_price'];
});
echo "<pre>";
print_r($array);
There is a complete example in the PHP manual about usort. Here's the modified version to solve your problem:
<?php
function cmp($a, $b)
{
if ($a['custom_price'] == $b['custom_price']) {
return 0;
}
return ($a['custom_price'] < $b['custom_price']) ? -1 : 1;
}
Below code will solve your problem,
usort($array, function($a, $b) {
if($a['custom_price']==$b['custom_price']) return 0;
return $a['custom_price'] > $b['custom_price'] ? 1 : -1;
});
Updated function
usort($array, function($a, $b) {
return $a['custom_price'] > $b['custom_price'];
});

Sort multidimensional array by keys - fails on duplicates [duplicate]

This question already has answers here:
Sort multi-dimensional array by specific key
(6 answers)
Closed 7 years ago.
I have a function sortBy() that I use to sort multidimensional arrays by a particular key. Here is a sample array:
Array
(
[0] => Array
(
[id] => 4
[type] => 1
[game] => 1
[platform] => 0
[TotalPot] => 7550
)
[1] => Array
(
[id] => 5
[type] => 0
[game] => 2
[platform] => 0
[TotalPot] => 7500
)
)
Here is the function
function sortBy($arr, $field='id', $order=1) {
$a = array();
if ( !is_array($arr) )
return false;
foreach($arr as $subArr) {
$a[$subArr[$field]] = $subArr;
}
if ( $order == 1 ) sort($a);
else rsort($a);
return $a;
}
In this case, calling sortBy($array, 'TotalPot'); would work fine, because the two values for TotalPot are different. However, if you run this example and set both TotalPot fields to $7500, it overwrites the first occurrence with the latter.
What would be the best way to make this function allow for two items with the same value but still keep them in relevant order? I thought about adding another character, an A or 1 to the end, but this seems sloppy and not very predictable, so a better course of action would be greatly appreciated.
You can simplify your code and just use usort(), e.g.
function sortArrayByField(array &$arr, $field = "id", $ASC = TRUE) {
usort($arr, function($a, $b)use($field, $ASC){
if($a[$field] == $b[$field])
return 0;
return $a[$field] > $b[$field] ? $ASC : !$ASC;
});
}
Then just call it like this:
sortArrayByField($array, "TotalPot", TRUE);
print_r($array);
The reason they are getting overwritten is because you're creating an array where the index is the value of the totalPot.
If there are duplicates, then you will only have one array element with the totalPot.
Easiest way is just to usort this:
<?php
$array = [
[
"id" => 4,
"type" => 1,
"game" => 1,
"platform" => 0,
"TotalPot" => 7550
], [
"id" => 5,
"type" => 0,
"game" => 2,
"platform" => 0,
"TotalPot" => 7500
]
];
usort($array, function($a, $b) {
return $a['TotalPot'] - $b['TotalPot'];
});
print_r($array);
Output:
Array
(
[0] => Array
(
[id] => 5
[type] => 0
[game] => 2
[platform] => 0
[TotalPot] => 7500
)
[1] => Array
(
[id] => 4
[type] => 1
[game] => 1
[platform] => 0
[TotalPot] => 7550
)
)
You can also make this a function:
function sortBy($arr, $field='id', $order=1) {
usort($arr, function($a, $b) use ($field, $order) {
if ($order == 1)
return $a[$field] - $b[$field];
else
return $b[$field] - $a[$field];
});
}

How can I sort an array by a key in PHP? [duplicate]

This question already has answers here:
How to Sort a Multi-dimensional Array by Value
(16 answers)
Closed 10 years ago.
I have an array with a bunch of keys. I want to sort one of the keys by their values.
Array (
[0] => stdClass Object (
[id] => 1
[question] => Action
[specific_to_movie_id] => 1
[total_yes] => 4 )
[1] => stdClass Object (
[id] => 2
[question] => Created by DC Comics
[specific_to_movie_id] => 1
[total_yes] => 1 )
[2] => stdClass Object (
[id] => 3
[question] => Christian Bale
[specific_to_movie_id] => 1
[total_yes] => 1 )
)
The array looks like that above, and I want to sort by "Total_yes"
How can I go about doing this in PHP?
Because it's a little more complex than a standard array sort, you'll need to use usort:
function compare_items( $a, $b ) {
return $a->total_yes < $b->total_yes;
}
$arrayToSort = array (
(object) array(
'id' => 1,
'question' => 'Action',
'specific_to_movie_id' => 1,
'total_yes' => 4
),
(object) array(
'id' => 2,
'question' => 'Created by DC Comics',
'specific_to_movie_id' => 1,
'total_yes' => 1
),
(object) array(
'id' => 3,
'question' => 'Christian Bale',
'specific_to_movie_id' => 1,
'total_yes' => 1
)
);
usort($arrayToSort, "compare_items");
If you want to reverse the sort order, just change return $a->total_yes < $b->total_yes to use > (greater than) instead of < (less than)
you could use usort, like:
function cmp($a, $b) {
return $a < $b;
}
usort($your_array, "cmp");
You can use Usort() that use a specific compere function:
Definition and Usage
The usort() function sorts an array using a user-defined comparison
function.
Syntax
usort(array,myfunction);
array -Required. Specifies the array to sort
myfunction-Optional. A string that define a callable comparison function. The comparison function must return an integer <, =, or > than 0 if the first argument is <, =, or > than the second argument
<?php
function cmp($a, $b)
{
if ($a->total_yes == $b->total_yes) {
return 0;
}
return ($a->total_yes < $b->total_yes) ? -1 : 1;
}
usort($array, "cmp");
?>
You have object, therefore you need use [usort()][http://www.php.net/manual/en/function.usort.php]
usort($array, function($a, $b){
if ($a->total_yes == $b->total_yes)
return 0;
return ($a->total_yes > $b->total_yes) ? -1 : 1;});
print_r($array);

How to sort nested PHP array

Can anyone tell me how to sort an array by key?
I want to sort this array by price.
this is my input array format
Array
(
[0] => Array
(
[house_data] => Array
(
[id] => 532
[max_person] => 8
[max_bedrooms] => 4
)
[image] => uploads/123.jpg
[price] => 1950
)
[1] => Array
(
[house_data] => Array
(
[id] => 531
[max_person] => 8
[max_bedrooms] => 5
)
[image] => uploads/1234.jpg
[price] => 1495
)
}
Try usort (http://php.net/manual/en/function.usort.php)
You should have something like:
function cmp($a, $b)
{
if ($a['price'] == $b['price']) {
return 0;
}
return ($a['price'] < $b['price']) ? -1 : 1;
}
usort($table, "cmp");
For making it one dimensional use serialize($array) function , it goes like this :$a = array() ; //your multidimensional array$b = array(); //output arrayforeach ($a as $key=>$value){ $b[] = serialize($value);}echo $b ;
Use the array_multisort() function for multidimensional array sorting.

help sorting this array

So I am looking to sort the multi dimensional array below by "fk_page_id" ascending. Does anyone have any pointers. I think usort() is where I have to look but it seems like I cant find anyone with my specific array structure.
Array
(
[0] => Array
(
[title] => subpage of subpage!
[id] => 5
[long_title] =>
[fk_page_id] => 4
)
[1] => Array
(
[title] => about us subpage
[id] => 4
[long_title] =>
[fk_page_id] => 2
)
[2] => Array
(
[title] => about us
[id] => 2
[long_title] =>
[fk_page_id] => 1
)
)
function cmp($a, $b) {
if($a['fk_page_id'] == $b['fk_page_id']) {
return 0;
} else {
return $a['fk_page_id'] < $b['fk_page_id'] ? -1 : 1;
}
}
usort($yourarray, 'cmp');
if you're using PHP 5.3+:
define(ASC,1);
define(DESC,-1);
function colsort($array,$col,$order=ASC) {
usort(
$array,
function($a,$b) use($col,$order) {
return strcmp($a[$col],$b[$col])*$order;
}
);
return $array;
}
colsort($x,'fk_page_id');

Categories