I have below json outout. Can anyone please suggest how to sort this according to "no_count" column?
$arr= {"UserHeader":[
{"id":"154", "no_count":15},
{"id":"155", "no_count":11},
{"id":"158", "no_count":13},
{"id":"159", "no_count":31},
{"id":"164", "no_count":11}
]}
I have used USORT but no luck. The code is not working and give me the same array without sorting.
usort($arr, function($a, $b) { //Sort the array using a user defined function
return $a->no_count > $b->no_count ? -1 : 1; //Compare the scores
});
print_r($arr);
Might be a small formatting error.
Thanks
I did some corrections :
$arr = json_decode('{"UserHeader":[
{"id":"154", "no_count":15},
{"id":"155", "no_count":11},
{"id":"158", "no_count":13},
{"id":"159", "no_count":31},
{"id":"164", "no_count":11}
]}');
usort($arr->UserHeader, function ($a, $b) { //Sort the array using a user defined function
return $a->no_count > $b->no_count ? -1 : 1; //Compare the scores
});
print_r($arr);
It should work as expected.
Related
I have a 2 dimensions array and need to sort it according to some of the second dimension values.
I tried using uksort, but it doesn't work:
$arr = array();
$arr[] = array('name'=>'test1', 'age'=>25);
$arr[] = array('name'=>'test2', 'age'=>22);
$arr[] = array('name'=>'test3', 'age'=>23);
$arr[] = array('name'=>'test4', 'age'=>29);
uksort($arr, "cmp");
print_r($arr);
function cmp($a, $b) {
if ($a['age']==$b['age']) return 0;
return ($a['age'] < $b['age']) ? -1 : 1;
}
Can anyone spot what am I doing wrong?
I think you are looking for uasort().
uksort() will order your array by keys, but you want to sort the arrays by their value.
uksort
Sort an array by keys using a user-defined comparison function
Sorting array by keys means that you take value of a key (in your case it is the same string age for all subarrays). And you sort by value.
So usort is enough - fiddle.
I'm new to php and I feel that this language has some really good set of sorting functions for arrays
I have an input array below containing the books , readers and price
$input[]=array("Harrypotter","John",50);
$input[]=array("Twilight","John",60);
$input[]=array("Harrypotter","Jack",80);
$input[]=array("Gonegirl","marion",90);
$input[]=array("Gonegirl","test",90);
$input[]=array("Gonegirl","John",90);
$input[]=array("Gonegirl","eliza",90);
I want to sort the array on first field in such a way that the book which repeats more number of times should come first , the expected O/p is something like this
$input[]=array("Gonegirl","marion",90);
$input[]=array("Gonegirl","test",90);
$input[]=array("Gonegirl","John",90);
$input[]=array("Gonegirl","eliza",90);
$input[]=array("Harrypotter","Jack",80);
$input[]=array("Harrypotter","John",50);
$input[]=array("Twilight","John",60);
I'm able to copy the first field in separate array and get the occurrence by using array_count_values and i'm able to get the expected output through array_multi_sort but it sorts only by alphabetical order of the first field .
Any efficient way of arriving at the solution would be helpful !
You will first have to establish a count of how often each value occurs, then you can write a comparison function that sorts by those values:
$counts = array_count_values(array_map('current', $input));
usort($input, function (array $a, array $b) use ($counts) {
return $counts[$b[0]] - $counts[$a[0]];
});
This should work for you:
<?php
$input = array();
$input[]=array("Harrypotter","John",50);
$input[]=array("Twilight","John",60);
$input[]=array("Harrypotter","Jack",80);
$input[]=array("Gonegirl","marion",90);
$input[]=array("Gonegirl","test",90);
$input[]=array("Gonegirl","John",90);
$input[]=array("Gonegirl","eliza",90);
function cmp($a, $b) {
return strcmp($a[0], $b[0]);
}
usort($input, "cmp");
print_r($input);
?>
array_multisort(array_map('count', $input), SORT_DESC, $input);
PS: From PHP Sort a multidimensional array by number of items
Update:
array_multisort(array_map(function ($fld) {return $fld[0];}, $input), SORT_ASC, $input);
I'm reading from a text file that has 2 columns. name,rank So it looks like this:
quxerm,6
brock,5
chris,15
So the 2d array looks like [0][0] = quxerm and [0][1]=6 [1][0] = brock [1][1]=5
I already have them into a 2d array like I showed above.
I need to sort these values in descending order by the integer column. How can I sort this?
#CBergau's answer is almost perfect but the order will be ascending instead of descending.
To get it descending just switch the return values of the compare function which is called by usort. See http://www.php.net/manual/en/function.usort.php for more information.
function cmp(array $a, array $b) {
return ($a[1] < $b[1]) ? 1 : -1;
}
usort($arr, 'cmp');
Example: http://codepad.org/QRTQLxTh
You could also extend the compare function for example to order ascending by name when the rank is the same by using strcmp. See http://www.php.net//manual/en/function.strcmp.php for more information.
function cmp(array $a, array $b) {
if ($a[1] == $b[1]) {
return strcmp($a[0], $b[0]);
}
return ($a[1] < $b[1]) ? 1 : -1;
}
Example: http://codepad.org/SeRTE3Ym
Note: I've not enough reputation yet to just comment on #CBergau's answer.
Use map instead, and then you can use all the functions relatives to maps like this.
take the array as arr[i][j].
try comparing only by changing the values of i.
for(int i=0;i<3;i++)
for(int k=1;k<3;k++)
if(arr[i][1]>arr[k][1])
max=i
and you can retrieve max by :-
arr[max][0]//name of max
arr[max][1]//value of max
$sorted = array();
foreach($yourArray as $a){
$sorted[$a[1]] = $a[0];
}
ksort($sorted);
vardump($sorted);
This should sort by the integer column:
usort(
$data,
function ($arrayOne, $arrayTwo) {
return ($arrayOne[1] < $arrayTwo[1]) ? -1 : 1;
}
);
If there are no duplicate names, you can simply assign the rank for the key (name), and sort that array while preserving keys.
$data["quxerm"] = 6;
$data["brock"] = 5;
$data["chris"] = 15;
asort($data, SORT_NUMERIC);
How to sort following php array with its 'zindex' key value
$array = array('the-1'=> array('name'=>'lorem','pos'=>array('top'=>'90','left'=>'80'),'zindex'=>2),
'the-2'=> array('name'=>'ipsum','pos'=>array('top'=>'190','left'=>'180'),'zindex'=>1),
'the-3'=> array('name'=>'lorem ipsum','pos'=>array('top'=>'20','left'=>'30'),'zindex'=>3)
)
Is there any php function for getting the output as follows,
$array = array(
'the-2'=> array('name'=>'ipsum','pos'=>array('top'=>'190','left'=>'180'),'zindex'=>1),
'the-1'=> array('name'=>'lorem','pos'=>array('top'=>'90','left'=>'80'),'zindex'=>2),
'the-3'=> array('name'=>'lorem ipsum','pos'=>array('top'=>'20','left'=>'30'),'zindex'=>3)
)
usort($array, function($a, $b) {
if ($a['name'] == $b['name']) {
return 0;
}
return ($a['name'] < $b['name']) ? -1 : 1;
});
This should do the trick for you... It did for me ;)
usort($array,function($el1,$el2){
return $el1-$el2;
});
Requires PHP5.3
if you need older versions' support replace anonymous function by usual one
I have tried adapting this code to use to sort a multidimensional array on a named key/field. The field is an integer what I need to sort smallest to biggest.
function myCmp($a, $b)
{
return strcmp($a["days"], $b["days"]);
}
uasort($myArray, "myCmp");
This sorts the arrays as I need but in the wrong order. At the moment it sorts biggest to smallest, not using natural order. I need to sort smallest to biggest in natural order (eg 2 comes before 5, 12 and 24).
strnatcmp() is your friend
e.g. (using a php 5.3 closure/anonymous function):
<?php
$myArray = array( 'foo'=>array('days'=>2), 'bar'=>array('days'=>22), 'ham'=>array('days'=>5), 'egg'=>array('days'=>12) );
uasort($myArray, function($a, $b) { return strnatcmp($a["days"], $b["days"]); });
foreach($myArray as $k=>$v) {
echo $k, '=>', $v['days'], "\n";
}
prints
foo=>2
ham=>5
egg=>12
bar=>22
You can just reverse the parameters of strcmp :
function myCmp($a, $b)
{
return strcmp($b["days"], $a["days"]);
}
uasort($myArray, "myCmp");
Since you want to sort in natural order you should not be using strcmp, you can do:
function myCmp($a, $b)
{
if ($a['days'] == $b['days']) return 0;
return ($b['days'] > $a['days']) ? -1 : 1;
}
Here is a working example.