cupakob
cupakob

Reputation: 8541

get only 5 elements from array

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

Upvotes: 2

Views: 11998

Answers (5)

cupakob
cupakob

Reputation: 8541

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..

Upvotes: 0

Georg Schölly
Georg Schölly

Reputation: 126165

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.

Upvotes: 0

Dan
Dan

Reputation: 1412

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 --> https://www.php.net/manual/en/function.array-multisort.php

Upvotes: 0

Greg
Greg

Reputation: 10360

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...)

Upvotes: 2

Gumbo
Gumbo

Reputation: 655649

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);

Upvotes: 7

Related Questions