dsrjs86444 2016-12-19 14:53
浏览 98
已采纳

PHP中的反向数组,索引错误

In PHP, I have an array like this:

Array ( 
    [12] => Dec 
    [01] => Jan 
    [02] => Feb 
    [03] => Mar 
    [04] => Apr 
    [05] => May 
    [06] => Jun 
    [07] => Jul 
    [08] => Aug 
    [09] => Sep 
    [10] => Oct 
    [11] => Nov 
) 

I then do something like this: $reverse_months = array_reverse($months);

What I don't understand is why the result coming out like this:

Array ( 
    [0] => Nov 
    [1] => Oct 
    [09] => Sep 
    [08] => Aug 
    [07] => Jul 
    [06] => Jun 
    [05] => May 
    [04] => Apr 
    [03] => Mar 
    [02] => Feb 
    [01] => Jan 
    [2] => Dec 
)

You can clearly see the last three months of the years got wrong indexes compare to original $months array :-(

Could anyone is kind enough to explain why this weird behavior happens and how can I fix it please? The outcome result is my desirable outcome except the wrong array index for month Oct, Nov and Dec. Thank you!

  • 写回答

1条回答 默认 最新

  • dqe9657 2016-12-19 14:58
    关注

    10, 11 and 12 are numeric keys, where 01, 02 and so on are named keys, what php does is reenumerating the numbered keys. There are 3 of them so 0,1,2. Named keys are not reenumerated (How should they ?). To also preserve integer keys, use

    array_reverse($months, true);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥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 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看