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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?