...

View Full Version : How to widdle a large array down to the top 3 values?



darkus
05-16-2010, 04:53 PM
I have a large dynamically created array arranged as follows



[9693] => 2
[9658] => 41
[9654] => 42
[9640] => 24
[9634] => 4
[9613] => 29
[9624] => 433
[9620] => 5



The values (2, 41, 42, 24, etc..) are the # of items associated with the key (9693, 9658, 9654, etc...).

What I want to do is maintain the same order but cut the array down to only the top 3 items in this array based on the values (ie. the number of items associated with that key).

so that my final array would look like this

[9658] => 41
[9654] => 42
[9624] => 433


Does anyone have any clue how to tackle this one?

Thanks!!

Fou-Lu
05-16-2010, 05:20 PM
Easiest way is to copy the array, sort it, and retrieve the first three.


$aTemp = $yourArray;
asort($aTemp, SORT_NUMERIC);
$aOnlyThree = array_slice($aTemp, 0, 3, true);
unset($aTemp);

mlseim
05-16-2010, 05:20 PM
If you are filling this array by using a MySQL query, let us know (that's where the real solution would be).

Otherwise, see examples here.
http://www.developertutorials.com/tutorials/php/sorting-array-php-051114/page1.html

Scroll down for associative array sorting.
Sort descending, and then pick the first 3 off the top.

If I missed the point of your post, let us know. I'm not sure if that's what you mean.

Phil Jackson
05-16-2010, 05:28 PM
<?php
$array = array(
'9693' => 2,
'9658' => 41,
'9654' => 42,
'9640' => 24,
'9634' => 4,
'9613' => 29,
'9624' => 433,
'9620' => 5);

$foo = array_flip($array);
arsort($foo, SORT_NUMERIC );
$foo = array_slice(array_flip($foo), 0, 3, true);
print_r($foo);

?>




Array
(
[9693] => 2
[9658] => 41
[9654] => 42
)

Phil Jackson
05-16-2010, 05:31 PM
[9658] => 41
[9654] => 42
[9624] => 433
Think I got it wrong... you want to order by key?? or by val??

darkus
05-16-2010, 06:25 PM
Thanks guys, I actually got it working by mixing a few suggestions you guys gave!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum