usort function result is wrong - php

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'];
});

Related

Sort Multi dimensional array by Value and not include to sorting if priority value is 0

I have to sort below given array by Priority. If priority value is 0 then not include in sorting array. I have tried many ways but not getting output as expected.
Array
(
[recently_viewed] => Array
(
[priority] => 1
[no_of_products] => 1
)
[recently_visited_cat] => Array
(
[priority] => 1
[no_of_products] => 1
)
[last_ordered_items] => Array
(
[priority] => 3
[no_of_products] => 3
)
[searched_based] => Array
(
[priority] => 0
[no_of_products] => 4
)
[cart_based] => Array
(
[priority] => 1
[no_of_products] => 5
)
[wishlist_based] => Array
(
[priority] => 1
[no_of_products] => 6
)
[sku_based] => Array
(
[priority] => 0
[no_of_products] => 7
)
)
Please help me with this.
You can use array_filter() function to exclude records with 0 priority. After it you can sort the array with help uasort() function. For example:
$arr = array_filter($arr, function($element) {
return $element['priority'] > 0;
});
uasort($arr, function ($a, $b) {
if ($a['priority'] === $b['priority']) {
return 0;
}
return ($a['priority'] < $b['priority']) ? -1 : 1;
});
You can us array_filter (doc - for check bigger then 0) and then uasort (doc):
$arr = [];
$arr["recently_viewed"] = ["priority" => 1, "no_of_products" =>1];
$arr["searched_based"] = ["priority" => 0, "no_of_products" =>4];
$arr["last_ordered_items"] = ["priority" => 3, "no_of_products" =>3];
$arr = array_filter($arr, function ($e) {return $e["priority"];});
uasort($arr, function($a, $b) {
return $a['priority'] - $b['priority'];
});
Live example: 3v4l
You can use array_filter with callback function to remove the values with ZERO
$arr = array_filter($arr, function ($e) {return $e["priority"];});
This will remove all the sub-array which has priority values ZERO.
Now you can apply usort to sort the array
usort($arr, function($a, $b) {
return $a['priority'] <=> $b['priority'];
});
See Working Code Live

Array sorting by key value in php [duplicate]

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);

Sorting a multi-dimensional Array by value

I have this array and I want to sort it (ASC)?
$stand_array[$player_name][$player_points] = $player_rank;
print_r
Array
(
[Player1] => Array
(
[50] => 5.7
)
[Player2] => Array
(
[40] => 4.2
)
[Player3] => Array
(
[30] => 3.7
)
[Player4] => Array
(
[20] => 2.3
)
[Player5] => Array
(
[10 => 1.5
)
[Player6] => Array
(
[60] => 6.3
)
)
Would you like to help me to solve this array on $player_rank (ASC)?
NB: I tried this function, but it did not work:
function sortByOrder($a, $b) {
return $a[$player_rank] - $b[$player_rank];
}
usort($myArray, 'sortByOrder');
The variable $player_rank is not visible from the sortByOrder function scope. Also, the indexes is different in each player array, so you need to access it like this:
function sortByOrder($a, $b)
{
$a = end($a);
$b = end($b);
if ($a == $b)
{
return 0;
}
return ($a < $b) ? -1 : 1;
}
usort($myArray, 'sortByOrder');
And if you want to save keys in $myArray then you must use the uasort function instead of usort.

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.

Categories