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);
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 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.
i have an array with the values of statistics taken from 2 executions and their difference. the name of the statistic is the key and it is unknown to me. I want to maintain index association
it is like this
$array["statistic_name_1"][0] = 5
$array["statistic_name_1"][1] = 4
$array["statistic_name_1"][2] = 1
$array["statistic_name_2"][0] = 10
$array["statistic_name_2"][1] = 4
$array["statistic_name_2"][2] = 6
$array["statistic_name_3"][0] = 15
$array["statistic_name_3"][1] = 10
$array["statistic_name_3"][2] = 5
...
and I want to sort it descending numerically according to the difference of the executions (which is the [key][2])
i have tried asort but i cant find a way to tell it to sort according to the difference
Try something like this:
function cmp($a, $b)
{
return $b[2] - $a[2]
}
uasort($array, "cmp");
http://www.php.net/manual/en/function.uasort.php
To put it all on one line you can do:
uasort($array, function($a, $b){ return $b[2] - $a[2] });
Use uasort to maintain keys association
uasort($array,function ($a,$b){
if ($a[2] == $b[2]) {
return 0;
}
return ($a[2] > $b[2]) ? -1 : 1;
});
I am creating a search capability for a forum program I'm building. At one point I have an array called searchResults which is numeric and contains 'score' as one of its dimensions (others are 'timeStarted', 'authorUID', and 'TID')
So, this array is in disarray at this point and I need to organize it to where $searchResults[1] will be the highest 'score' and [2] will have the second highest, etc. I looked at array_multisort on php.net but got rapidly lost in how it worked. So how would I sort $searchResults in numeric order (rearrange the keys) descending with a descending order of a further dimension 'sort' as the sorting mechanism? There really isn't any code to go with it but if you need a layout of how the array looks, here you go:
$searchResults:
[1] - ['timeStarted']
['authorUID']
['score'] <- Need to sort first dimension by this value descending
['TID']
etc.
Thanks for any help.
usort allows sorting by any specified comparison function
$cmp = function($a,$b) {return $b['score'] - $a['score'];};
usort($searchResults, $cmp);
In this case, $cmp is a function that compares two elements $a and $b of $searchResults based on value of ['score']. $cmp returns 0 for equality, negative val if $a['score'] is greater, positive val if $b['score'] is greater. It would normally be the other way around, but a descending sorting order is desired.
The function you want is usort. Look at example #2:
<?php
function cmp($a, $b)
{
return strcmp($a["fruit"], $b["fruit"]);
}
$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";
usort($fruits, "cmp");
while (list($key, $value) = each($fruits)) {
echo "\$fruits[$key]: " . $value["fruit"] . "\n";
}
?>
The output:
$fruits[0]: apples
$fruits[1]: grapes
$fruits[2]: lemons
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.