简体   繁体   中英

Select values in an array with specific conditions in PHP

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM