tags:

views:

1486

answers:

5

Hi all,

my array is setup as follow:

array
  'testuri/abc' => 
    array
      'label' => string 'abc' (length=3)
      'weight' => float 5
  'testuri/abd' => 
    array
      'label' => string 'abd' (length=3)
      'weight' => float 2
  'testuri/dess' => 
    array
      'label' => string 'dess' (length=4)
      'weight' => float 2
  'testuri/gdm' => 
    array
      'label' => string 'gdm' (length=3)
      'weight' => float 2
  'testuri/abe' => 
    array
      'label' => string 'abe' (length=3)
      'weight' => float 2
  'testuri/esy' => 
    array
      'label' => string 'esy' (length=3)
      'weight' => float 2
  'testuri/rdx' => 
    array
      'label' => string 'rdx' (length=3)
      'weight' => float 3
  'testuri/tfc' => 
    array
      'label' => string 'tfc' (length=3)
      'weight' => float 3

I want to get/filter the 5 elements with bigges 'weight'. Is there a php function to make this?

PS. My idea was to use foreach

+2  A: 

Sort the array by the weight value in descending order and then get the first five values:

function cmpByWeight($a, $b) {
    return $b['weight'] - $a['weight'];
}
uasort($array, 'cmpByWeight');
$firstFive = array_slice($array, 0, 5);
Gumbo
usort won't preserve the array-keys
Greg
+2  A: 

You'd be better using uasort with a callback that compares the 'weight' index of the passed values, and then array_slice to grab the first 5 elements (or last 5 depending on which way you sort...)

Greg
I wouldn't sort the whole array. This has a complexity of O(n*log n), using a heap or a simple list of the top5 elements it's down to O(k*log n) or O(k*n)
Georg
A: 

I would use array_multisort() and then grab the first 5 values.

array_multisort($weight, SORT_DESC, $label, SORT_ASC, $YOUR_ARRAY)

Then just grab $YOUR_ARRAY[0] - $YOUR_ARRAY[4] or iterate over the array to grab the first 5

[EDIT] here's a link to the function --> http://us3.php.net/manual/en/function.array-multisort.php

Dan
A: 

As far as I know there isn't.

You could use a heap for this, but for only 5 elements I'm not sure it's faster than just storing the top 5.

Georg
A: 

My English is not the best, i will try to explain, what i need. i can sort the array....but in the example above i have following:

1x weight 5
2x weight 3
5x weight 2

So...if I grab the first 5 elements, the another 3 with weight 2 will be ignored. So i need all 5 elements with weight 2....and so i have an array with 7 items.

Another example:

2x weight 5
4x weight 2
7x weight 1

All elements with weight1 must be ignored, So i get 6 elements in a new array..

cupakob