简体   繁体   中英

php array how to filter dynamic number values in a set range?

I have a function that returns an array with the values as numbers. The array values are dynamic and will change all the time.

The numbers have a set range, with the higher value determined by the last digit (ie _1,2,3)

Im not sure if range() is the answer but I'll include them here.

eg of ranges:

100_1 100_2 100_3 101_1 101_2 101_3 102_1 102_2 102_3 103_1 103_2 103_3 104_1 104_2 104_3

For this example the returned array is as follows:

Array
(

[0] => 100_1
[1] => 100_2
[2] => 100_3
[3] => 101_1
[4] => 102_1
[5] => 102_2
[6] => 103_1
[7] => 103_2
[8] => 103_3
[9] => 104_1
[10] => 104_2

)

What I would like is to foreach(), (or similar) the array and return it like this:

Array
(

[1] => 100_3
[2] => 101_1
[3] => 102_2
[4] => 103_3
[5] => 104_2

)

If you notice only the higher values have been returned according to the set range.

As I am a newbie to php is there a simple solution I can understand? I appreciate any help thanks.

I was bored. This should do it:

natsort($array);

foreach($array as $value) {
    $parts = explode('_', $value);
    $result[$parts[0]] = $value;
}
$result = array_values($result);
  1. You need to natsort first to make this work.
  2. Then explode to get the base number for the key (ie 100 ) and the extra number for the value (ie 1 ). The next 100 etc. will overwrite the previous and store the extra number (ie 2 ), etc.
  3. Finally, array_values will return a re-indexed $result array.

I'm not 100% sure if this is the most efficient way to do it, but it works.

$myArray = array("100_1", "100_2", "100_3", "101_1", "102_1", "102_2", "103_1", "103_2", "103_3", "104_1", "104_2");
$resultArray = array();

foreach($myArray as $entry)
{
    $parts = explode("_", $entry);
    $found = FALSE;

    // I really don't like that I'm iterating this every time
    // this is why I think there might be a more efficient way.
    foreach($resultArray as $key => $resultEntry)
    {
        $resultParts = explode("_", $resultEntry);

        // if the part before the underscore matches an entry in the array
        if($parts[0] == $resultParts[0])
        {
            $found = TRUE;

            // see if the part after the underscore is greater than
            // the part after for the entry already in the result
            if((int)$parts[1] > (int)$resultParts[1])
            {
                $resultArray[$key] = $entry;
            }
        }
    }

    if(!$found)
    {
        $resultArray[] = $entry;
    }
}

DEMO

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