2018-04-12 20:29
浏览 44


I have a function that is looping over a bunch of items that each look something like this:


I would like to re-order each item so that instead of going in ascending order, it goes something like col-one, col-four, col-three, col-two. Is there a relatively simple method that can accomplish this type of arbitrary sorting?

To be clear, I want the result to look like the following:



图片转代码服务由CSDN问答提供 功能建议

我有一个循环遍历一堆项目的函数,每个项目看起来像这样: \ ñ

 <代码> [\ N { “目标”: “COL-一个”, “值”:0.261},\ N { “目标”: “COL-2”, “值”:0.881}  \ N { “目标”: “COL-3”, “值”:0.571},\ N { “目标”: “COL-4”, “值”:0} 

我想重新订购每个项目,以便不是按升序排列,而是类似col-one,col-four,col-three,col-two。 是否有一种相对简单的方法可以完成这种类型的任意排序?


 {“Target  “:”col-three“,”Value“:0.571},


  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

  • dongxian3852 2018-04-12 20:39

    If you have an array that defines the sort order, like:

    $order = ['col-one', 'col-four', 'col-three', 'col-two'];

    You can pass it into the usort comparison function and look up the sort index there. I think it's easier if you flip it so the text becomes the key.

    $order = array_flip($order);
    usort($items, function($a, $b) use ($order) {
        return $order[$a->Target] <=> $order[$b->Target];

    If you don't flip it first, you have to array_search repeatedly instead. (Unless there's a better way I don't know of.)

    usort($items, function($a, $b) use ($order) {
        return array_search($a->Target, $order) <=> array_search($b->Target, $order);
    解决 无用
    打赏 举报

相关推荐 更多相似问题