My array will only contain a specific set of characters. However these characters could appear in the array in any order.
I want to rearrange this array so they are always in the same order.
Is this possible as some times the array will contain 1 entry other times upto 4 entries possibly more.
The characters that could appear in the array will be () ^ & ! #
But I will have no idea what order until the form is submitted.
Ideally I always want them to be in the following order :
! # ^ & ()
Is this possible ?
Thanks
Try something like this
// establish the sort order
$order = array("!","#", "^", "&", "(",")");
// usort with indexes of $orderArray
usort($arr, function($a, $b) use($order) {
$aIdx = array_search($a, $order);
$bIdx = array_search($b, $order);
return $aIdx - $bIdx;
});
You could use one of the built in PHP sort functions, depending on your requirements.
Probably the two you would most be interested in are
asort - Sort an array and maintain index association
sort - This function sorts an array. Elements will be arranged from lowest to highest when this function has completed.
Though, there are quite a few others - See Sorting Arrays from Php Manual
Or, alternatively, if the resulting sort order does not match what you are desiring, you could use usort, which allows you to define a custom sort function
Something like this should work
$arrayToSort = array('#','&','()','^','!');
$order = array( '!', '#', '^', '&', '()');
function compare($a,$b) {
global $order;
$indexa = array_search($a,$order);
$indexb = array_search($b,$order);
return ($indexa < $indexb) ? -1 : 1;
}
usort($arrayToSort, $compare);
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.
Here is a snippet of my array that is used in php 5.3.x :
$arr[$category][$item][$attr_qty] = 3;
$arr[$category][$item][$attr_price] = 12.00;
$category are arbitrary integers, as are $item, as are $attr_qty and $attr_price.
Is there a quick way of sorting, by $attr_qty, the items in each category?
Using integers makes the code easier, but I get the feeling I will have to use associative arrays.
You can use usort which allows you to specify a custom sorting function
usort($arr, 'customSortFunction');
function customSortFunction($a, $b)
{
if ($a['item']['attr_qty'] > $b['item']['attr_qty']) return 1; //First element is bigger
elseif ($a['item']['attr_qty'] < $b['item']['attr_qty']) return -1; //Second element is bigger
else return 0; //Both are equal
}
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 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