0

In PHP I have an array that looks like below, but with a lot of more values. I want to select only few values of this array with this conditions : 5 spares of each series with the minimum price. I have done something in my application but it seems very complicated for this simply condition. Do you have any idea that can help me to do this the more simply possible?

[0] => spare
    (
        [price] => 156
        [name] => alpha
        [serie] => green
)
  [1] => spare
        (
        [price] => 205
        [name] => beta
        [serie] => green
) 
[2] =>spare
    (
        [price] => 276
        [name] => gamma
        [serie] => red
)
[3] => spare
    (
        [price] => 207
        [name] => zeta
        [serie] => green
)….
Etienne
  • 408
  • 2
  • 9
  • 28

2 Answers2

1

sort array by usort and anonymous function and get a slice of needed elements

   usort($myArray, function($a, $b) {
        return $a['price'] - $b['price'];
    });
    $output = array_slice($myArray, 0, 5);
bxN5
  • 1,430
  • 2
  • 16
  • 27
1

You can follow the following steps.

  1. Create multiple arrays by serie from that above array.

  2. Sort each array by the price. You can get help from this link to short the array. Link

  3. Display first 5 element from each array or you can use array_slice function to get first 5 element.

Community
  • 1
  • 1
Suman Biswas
  • 853
  • 10
  • 19