I have an array of products
$products = array_count_values($products);
now I have an array where $key is product number and $value is how many
times I have such a product in the array.
I want to sort this new array that product with the least "duplicates" are
on the first place, but what ever I use (rsort, krsort,..) i loose product
numbers (key).
any suggestions?
thanks.
Take a look at arsort() as an alternative to rsort() (and that family of functions).
Generally, the 'Sorting arrays' page on php.net might be useful to you - it's a comparison of PHP's array sorting functions based on what they sort, what direction they sort in, and whether they maintain the keys while sorting.
Mind you, for the sake of completion:
Going by 'now I have an array where $key is product number and $value is how many times I have such a product in the array. I want to sort this new array that product with the least "duplicates" are on the first place', you probably want asort() (the pendant to sort()).
Your comment example, using asort():
$arr = array(
1 => 3,
2 => 2,
5 => 3,
9 => 1
);
asort($arr);
print_r($arr);
yields:
Array
(
[9] => 1
[2] => 2
[1] => 3
[5] => 3
)
You want to use asort():
This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.
rsort() was wrong from the first place anyway (and so are any other sorting functions that have the r (for reverse) in it), as it would sort the array from highest to lowest.
asort() sorts from lowest to highest:
<?php
$array = array('f'=>1, 'a'=>2, 'c'=>5);
asort($array);
print_r($array);
gives
Array
(
[f] => 1
[a] => 2
[c] => 5
)
Note: These functions sort the arrays in-place. They do not return a sorted array. The return values is:
(..) TRUE on success or FALSE on failure.
Try using asort() or arsort() or any other sort function that maintains index association.
You should use asort() PHP function.
asort() is array sort, not ascending sort.
dsort doesn't exist. The function you are looking for is arsort() - array reverse sort.
https://www.php.net/manual/en/function.asort.php
https://www.php.net/manual/en/function.arsort.php
Just a thought;
asort - sorts ascending (low to high)
perhaps try
dsort - descending (high to low)
Related
I need an array sorted by Unix timestamp values. I attempted to use both ksort and krsort before realising that occasionally the timestamp values might be the same (and you cannot have duplicate keys in arrays).
Here's an example array I may be faced with:
$array = array(
[
"unix" => 1556547761, // notice the two duplicate unix values
"random" => 4
],
[
"unix" => 1556547761,
"random" => 2
],
[
"unix" => 1556547769,
"random" => 5
],
[
"unix" => 1556547765, // this should be in the 3rd position
"random" => 9
]
);
So what I'm trying to do is sort them all based on each child arrays unix value, however I cannot figure out how to do so. I have tried countless insane ways (including all other sort functions and many, many for loops) to figure it out - but to no avail.
All help is appreciated.
You can use usort which sort your array by given function
Define function as:
function cmpByUnix($a, $b) {
return $a["unix"] - $b["unix"];
}
And use with: usort($array, "cmpByUnix");
Live example: 3v4l
Notice you can also use asort($array); but this will compare also the "random" field and keep the key - if this what you need then look at Mangesh answer
array_multisort() — Sort multiple or multi-dimensional arrays
array_columns() — Return the values from a single column in the input array
You can use array_multisort() and array_column(), then provide your desired sort order (SORT_ASC or SORT_DESC).
array_multisort(array_column($array, "unix"), SORT_ASC, $array);
Explanation:
In array_multisort(), arrays are sorted by the first array given. You can see we are using array_column($array, "unix"), which means that the second parameter is the order of sorting (ascending or descending) and the third parameter is the original array.
This is the result of array_column($array, "unix"):
Array(
[0] => 1556547761
[1] => 1556547761
[2] => 1556547765
[3] => 1556547769
)
This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.
Note:If two members compare as equal, their relative order in the sorted array is undefined.
Refer : https://www.php.net/manual/en/function.asort.php
asort($array);
echo "<pre>";
print_r($array);
echo "</pre>";
It will give you the output as
Array
(
[1] => Array
(
[unix] => 1556547761
[random] => 2
)
[0] => Array
(
[unix] => 1556547761
[random] => 4
)
[3] => Array
(
[unix] => 1556547765
[random] => 9
)
[2] => Array
(
[unix] => 1556547769
[random] => 5
)
)
You can keep the array key [1],[0],[3],[2]) as it is Or you can keep it as sequential as per your requirement.
please view the following code with 2 arrays. i use multisort function with sort flags for ascending and numeric then display. as you can see in the output that array 2 starts with 100 when it should be last. please explain what is causing this and how to sort it correctly. thank you.
<?php
$array1 = array(1,7,10,6);
$array2 = array(100,20,25,10);
array_multisort($array1, SORT_ASC, SORT_NUMERIC, $array2);
print_r($array1);
echo "<br>";
print_r($array2);
?>
output:
Array ( [0] => 1 [1] => 6 [2] => 7 [3] => 10 )
Array ( [0] => 100 [1] => 10 [2] => 20 [3] => 25 )
Ah, yes, array_multisort is a bit tricky to understand the first time round.
Basically the sort is lexicographical, a fancy word meaning that the first array is sorted and the second arrays elements are ordered according to the first array.
Look at your first (output) array and see the order and map it to the initial second array and you'll see whats happening.
So the second array you take the 1st, 4th , 2nd and 3rd elements.
If you just want plain sorting for multiple arrays then just do them one by one or over a loop.
i have an array that looks like this:
Array ( [2] => 2 [3] => 2 [1] => 1 )
i want to sort the array so the integers are in descending order
Array ( [3] => 2 [2] => 2 [1] => 1 )
is there a php function that can do that, i tried krsort, but i think that only works on strings as all it outputted "1".
Thanks
krsort is right but it changes the array (pass by reference), not returns a new one.
krsort($a);
print_r($a);
Try krsort(). Sorts an array by key in reverse order.
krsort($array);
Check out more information on sorting arrays
all it outputted "1".
Because you called it as:
$newarr = krsort($myarr);
and krsort() returns true/false on success/failure. The array is sorted in-place and is still referenced by $myarr.
Try:
print_r($arr);
krsort($arr, SORT_NUMERIC)
print_r($arr);
Hope it helps :)
$age=array("35","37","43");
print_r($age);
krsort($age,1);
print_r($age);
visit here for more help : - http://www.w3schools.com/php/func_array_krsort.asp
How do I sort an array with the highest points?
Example:
$sale = array();
Array
(
[UserA] => Array
(
[unsuccessful] => 0
[Points] => 31
[procesing] => 4
)
[UserB] => Array
(
[unsuccessful] => 4
[Points] => 200
[procesing] => 1
)
[UserC] => Array
(
[unsuccessful] => 3
[Points] => 150
[procesing] => 55
)
)
Sort by points, it should be in order: UserB, UserC, UserA
uasort($array, function($a, $b) {
return $b['Points'] - $a['Points'];
});
The uasort() and usort() functions take a callback that should specify exactly what makes one item greater or lower than another item. If this function returns 0, then the items are equal. If it returns a positive number, then the second item is greater than the first item. Else, the first item is greater than the second.
The difference between uasort() and usort() is that uasort() also keeps the keys, while usort() does not. Also take a look at the comparison of array sorting functions to find out about all the other ways you can sort arrays.
You can use the php function usort to provide your own custom sorting logic. See http://www.php.net/manual/en/function.usort.php
You may find USort helpful:
http://php.net/manual/en/function.usort.php
Also this other article on SO.
Sort multi-dimensional array with usort
I am working on a display screen for our office, and I can't seem to think of a good way to find the largest numerical value in a set of data in a two dimensional array. I've looked at using max() and also asort() but they don't seem to cope with a two dimensional array.
I'm returning my data through our mysql class, so the rows are returned in a two dimensional array.
Array(
[0] => Array(
[am] => 12,
[sales] => 981),
[1] => Array(
[am] => 43,
[sales] => 1012),
[2] => Array(
[am] => 17,
[sales] => 876)
)
I need to output a class when foreaching the data in my table for the AM with the highest sales value. Short of comparing them all in > if statements. I have tried to get max() on the array, but it returns an array, as it's look within the dimension. When pointing it at a specific dimension it returns the key not the value.
I figured that I could asort() the array and pop the top value off, store it in a variable and then compare against that in my foreach() loop, but that seems to have trouble sorting across two dimensions.
Lastly, I figured that I could foreach() the values, comparing them against the previous one each time, untill I found the largest. This approach however means storing every value, luckily only three, but then comparing against them all again.
Surely there must be a simpler way to achieve this, short of converting it into a single dimension array, then doing an asort() on that?
<?php
function customSort($a, $b)
{
if($a['sales'] == $b['sales'])
return 0;
else
return $a['sales'] < $b['sales'] ? -1 : 1;
}
usort($array, 'customSort');
?>
Is what I would do