PHP数组如何过滤一个设置范围内的动态数值


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

我有一个函数,它返回一个数组,其中的值为数字。数组的值是动态的,会一直改变。

数字有一个固定的范围,由最后一位数字(即_1,2,3)决定较大的值

我不确定range()是否是答案,但我将在这里包含它们。

。范围:

100 _1100 _2100年_3101 _1101 _2101年_3102 _1102 _2102年_3103 _1103 _2103年_3104 _1104 _2104年_3

对于本例,返回的数组如下:

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
)

我想要的是foreach(),(或类似的)数组,并像这样返回它:

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

如果您注意到根据设置范围只返回较大的值。

我是一个新手php有一个简单的解决方案,我可以理解吗?谢谢你的帮助。

我很无聊。应该这样做:

natsort($array);
foreach($array as $value) {
    $parts = explode('_', $value);
    $result[$parts[0]] = $value;
}
$result = array_values($result);
  1. 您需要首先使用natsort才能使此工作。
  2. 然后explode以获得键的基数(即100)和值的额外数字(即1)。下一个100等将覆盖前一个并存储额外的数字(即2),等等。
  3. 最后,array_values将返回一个重新索引的$result数组。

我不确定这是否是最有效的方法,但它是有效的。

$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;
    }
}
演示