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);
Related
Very simple but I was wondering why this is not working.
I'm trying shuffle an array and output the results (in a single line structure)
this is my code :
echo shuffle(array("A","B","C"))[0];
Small tweak needed here ;)
Your basic logic is a little bit wrong. You're interested in only one value, I assume? To solve it with that logic in mind, you can do it like this:
echo array_rand(array_flip(['A', 'B', 'C']));
Try below code
$arr = array("A","B","C");
shuffle($arr);
echo $arr[0];
I know that this is not the best solution for you, but it works!
print_r( ( $b=array('A', 'B', 'C') ) && shuffle($b) ? next($b) : null );
How this works:
Assign the array to the variable $b
Shuffle the variable $b
If the shuffle() succeeded:
return the next element in the array
If the shuffle() failed:
return null
Some might think: "Why didn't he used the current() function?"
Well, it seems that the function shuffle simply changes the order of the keys, but the pointer is always pointing to the same element. This means that current() will always return 'A'.
Apparently, this behaviour changed on PHP 5.4 to set the pointer to the first element.
TRY THIS SIMPLE FUNCTION
$my_array = array("A","B","C","D","E");
shuffle($my_array);
print_r($my_array);
You will need to pass the array in a seperate variable. Also, shuffle() itself just returns a boolean value, so you need to return an array element instead of the output of the function.
$ar = array("A","B","C");
shuffle($ar);
echo $ar[0];
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);
$mostmatched = function( $input to test, $array with given values)
The array contains diffrent numbers (10,30,50 ...) and I give an input (13) and the desired function should return the nearest value in the array (10).
Is there already a function like this? Else: Any suggestions how to achieve that?
usort($array, function ($a, $b) use ($input) {
return abs($input - $a) - abs($input - $b);
});
echo "Closest: $array[0]";
In other words: take the difference between $input and each value—smaller differences are closer—and sort the array by this. See https://stackoverflow.com/a/17364128/476 if this requires explanation.
Alternatively, simply loop through the array, keep track of the last smallest difference and replace it if you find a smaller difference. I'll leave the implementation of that as an exercise for the reader.
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.
I can get a sorted filename list with the following code:
$log_files = scandir(LLP_LOG_DIR);
$sorted = sort($log_files);
the filename format is X.log, where X is a progressive numeric value.
How can I solve the problem of getting
0.log
1.log
10.log
11.log
2.log
3.log
where the wanted result is
0.log
1.log
2.log
3.log
[..]
9.log
10.log
11.log
[..]
I can strip the ".log" string, sort them etc, but what is the most efficient way?
try natsort instead,
natsort($log_files)
Set the second parameter of sort to SORT_NUMERIC to have numeric sorting:
$sorted = $log_files;
sort($sorted, SORT_NUMERIC);
And note that sort sorts the array of the variable given with the first parameter. The return value of sort is just a boolean value.
Try natcasesort instead.
natcasesort($array);
because natsort is case sensitive.