Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting array after array_count_values

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.

like image 228
Muhammad Umer Avatar asked May 18 '10 11:05

Muhammad Umer


3 Answers

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
)
like image 179
pinkgothic Avatar answered Nov 19 '22 03:11

pinkgothic


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.

like image 24
Felix Kling Avatar answered Nov 19 '22 04:11

Felix Kling


Try using asort() or arsort() or any other sort function that maintains index association.

like image 3
Alix Axel Avatar answered Nov 19 '22 05:11

Alix Axel