dqdjfb2325 2014-08-04 19:34
浏览 54
已采纳

php数组如何过滤设定范围内的动态数值?

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 (i.e _1,2,3)

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

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

  • 写回答

2条回答 默认 最新

  • dqrsceg6279196 2014-08-04 19:46
    关注

    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 (i.e. 100) and the extra number for the value (i.e 1). The next 100 etc. will overwrite the previous and store the extra number (i.e. 2), etc.
    3. Finally, array_values will return a re-indexed $result array.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)