I have a array like this:
$array = array(
[1]=>'something',
[0.2]=>'something',
[0.1]=>'something',
[0.3]=>'something',
[0.10]=>'something'
);
Now i like to sort this array by key, so for that i am using this code:
uksort($array, 'strnatcasecmp');
The above code works fine, but the only problem is that i want to reverse the result.
For this purpose i used krsort , array_reverse , rsort after uksort, but all of them change uksort's result.
So have can i sort this array by key in natural order and reverse the result?
What i want should be like :
$array = array(
[1]=>'something',
[0.10]=>'something',
[0.3]=>'something',
[0.2]=>'something',
[0.1]=>'something'
);
Try this:
uksort($array, create_function('$a,$b', 'return -strnatcasecmp($a,$b);'));
Since you already use a variant of uksort (user-function defined sort), this version just reverses the order by inverting the result of the comparison function. I think it should work for you.
Alternatively try this:
uksort($array, 'strnatcasecmp');
$array = array_reverse($array, true);
Note the true parameter, that preserves your keys.
Update for modern PHP versions, since create_function is deprecated:
uksort($array, function ($a, $b) { return -strnatcasecmp($a, $b); });
Update for PHP 7.4 with new syntax (not released as of writing):
uksort($array, fn($a, $b) => -strnatcasecmp($a, $b));
For PHP 4+, you can use krsort:
krsort($array, SORT_NATURAL | SORT_FLAG_CASE);
Looks simpler to me, and it works the same as strnatcasecmp(). If you don't want it to be case sensitive, get rid of the SORT_FLAG_CASE flag.
I'm not a php programmer, but according to
http://www.php.net/manual/en/function.uksort.php
you should be able to write your own call back function for the comparison and then sort them anyway you want to.
asort() will sort by the key, arsort() will sort by the key and reverse the order.
Related
I have array like
$a = $b = $c = [];
$a['num'] = 10;
$b['num'] = 2;
$c['num'] = 4;
$arr = array($a,$b,$c);
then now I want to order array $arr by hash ['num']
result should be array($b,$c,$a)
I think I can re-order by for loop, but it looks not cool.
I think python has list in list but is it possible in PHP?
Is there any good idea to make this??
There is no easy way to do solve this problem. Basically you have to compare the elements inside the array.
You can just use usort function with your custom comparison function.
function compare($a, $b) {
return $a['num'] - $b['num'];
}
usort($arr,"compare");
You can also give an anonymous compare function to it. If you do not plan use your custom compare function again, I recommend you to use anonymous function.
usort($arr,function($a, $b){
return $a['num'] - $b['num'];
});
Do not forget
usort function does not return an array. It just returns TRUE on success or FALSE on fail and the array that you send as a parameter will sort.
You can use sort().
sort($arr);
The inner arrays are the same length, and all have the same single key, so sort() will compare them based on their contents and $arr will be sorted as if it was simply an array of integers.
There is an array of strings;
$arr=array('longstring','string','thelongeststring');
so the keys are:
0=>'longstring'
1=>'string'
2=>'thelongeststring'
I want to sort it by length of strings, from longest to shortest, but without changing their keys;
$arrSorted=array(**2**=>'thelongeststring', **0**=>'longstring', **1**=>'string');
I am working with PHP since 2 days so that is what I already know that could be helpful with this case:
...
usort($twoDim, 'sorting');
}
function sorting($a, $b) {
return strlen($b) - strlen($a);
}
That is giving me array with string sorted by length, but with new keys. Another thing is asort which sorts an array alphabetical and maintain its keys. But I have no idea how to do these two things in the same time...
Please help!
Use uasort:
uasort — Sort an array with a user-defined comparison function and maintain index association
usort doesn't maintain index associations.
Use it like this:
function sortByLength ($a, $b) {
return strlen($b) - strlen($a);
}
$arr = ['longstring', 'string', 'thelongeststring'];
uasort($arr, 'sortByLength');
print_r($arr);
eval.in demo
This returns:
Array
(
[2] => thelongeststring
[0] => longstring
[1] => string
)
...how to do these two things in the same time
You're almost there.
usort + asort = uasort.
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 would like to use the functionality of SORT_ASC, SORT_DESC with array_multisort()
but the problem is, it sorts my array like
test.1
test.10
test.2
test.3
test.4
test.5
it should be
test.1
test.2
test.3
test.4
...
test.10
currently using it like this
array_multisort(($sortc), (($sortby==='asc') ? SORT_ASC : SORT_DESC), $pool);
$sortc is the array I want to sort from the multi-dimensional array of $pool
I do know that natsort can do it properly, but it doesnt have the same functionality as array_multisort.
You want to use natural sort. Just add the SORT_NATURAL flag.
array_multisort(($sortc), (($sortby==='asc') ? SORT_ASC : SORT_DESC), SORT_NATURAL, $pool);
Im stuck on a sorting problem, I have an array with 10 numbers (1-10) and I need to sort the in the following way where 10 would come after 1, for example...
desired outcome
$arr['a1','a10','a2','a3','a4','a5','a6','a7','a8','a9'];
actual outcome
$arr['a1','a2','a3','a4','a5','a6','a7','a8','a9','a10'];
sort($arr);
$arr['a10','a1','a2','a3','a4','a5','a6','a7','a8','a9'];
I don't know the name of this type of sorting or how to perform it, if anyone could help me it would much appreciated.
NOTE: the numbers are part of a string
Try sort($arr,SORT_STRING) to explicitly treat the input as strings.
EDIT: Now that you've given your actual strings, try this:
usort($arr,function($a,$b) {
$a = explode("=",$a);
$b = explode("=",$b);
return $a[0] == $b[0] ? strcmp($a[1],$b[1]) : strcmp($a[0],$b[0]);
});
Sure, you want to sort alphabetically, not numerically.
sort($arr, SORT_STRING);
ref: http://php.net/manual/en/function.sort.php
You can change the behaviour of sort with it's second parameter.
Try this:
sort($arr, SORT_STRING);