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 orFALSE
on failure.
Try using asort()
or arsort()
or any other sort function that maintains index association.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With