douwu7168 2016-01-07 19:12
浏览 45
已采纳

在PHP中对数据数组进行排序的最佳方法

So I have the following data array:

array (size=10)
  0 => int 5
  1 => string '5B1' (length=7)
  2 => int 4
  3 => string '4B1' (length=7)
  4 => int 3
  5 => string '3B1' (length=7)
  6 => int 2
  7 => string '2B1' (length=7)
  8 => int 1
  9 => string '1B1' (length=7)

What I want to do is sort it to this:

array (size=10)
  0 => string 5B1
  1 => int '5' (length=7)
  2 => string 4B1
  3 => int '4' (length=7)
  4 => string 3B1
  5 => int '3' (length=7)
  6 => string 2B1
  7 => int '2' (length=7)
  8 => string 1B1
  9 => int '1' (length=7)

The hierarchy of the numbers never change although there is an additional level as seen here:

7 -> 6b2 -> 6b1 -> 6 -> 5b2 -> 5b1 -> 5 4b2 -> 4b1 -> 4 -> 3b2 -> 3b1 -> 3 -> 2b2 -> 2b1 -> 2 -> 1b2 -> 1b1 -> 1 -> b2 -> b1

I am wondering what is the best way to sort this in PHP?

On the one hand I am thinking of looping through the static hierarchy array from top to bottom and using this to order the dynamic array.

Any other suggestions?

  • 写回答

1条回答 默认 最新

  • dongzhuoxie1244 2016-01-07 19:42
    关注

    The answer to this was quite simple, Mark Baker put me on the right track.

    I originally used a convoluted mix between rsort, krsort and array_flip to get an almost working solution.

    Using rsort with the SORT_NATURAL flag did the trick.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能
  • ¥20 关于多单片机模块化的一些问题
  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃