dqudtskm49788 2012-11-28 19:47
浏览 68
已采纳

双排序数组

My array has sorting values from 1-6.

Array: 2 5 6 2 5 1 1

and then I can get the two's first before anything else for example.

So it would be like 2 2 5 6 5 1 1. But, then I need to sort by the other sorting values and dates.

Example: 2 2 1 1 5 5 6 and those also have dates attached to them and needs to be sorted in descending order.

Final example:

2 - 2012-06-02
2 - 2012-06-01
1 - 2012-03-05
1 - 2012-03-01
5 - 2012-08-09
5 - 2012-01-01
6 - 2012-11-29

My function looks like this at the moment and is used by the usort function. ObjektTyp is the sorting value, different numbers depending on what type of house it is. All these values comes from a XML-source.

function sort_by_type(&$array, $sort = NULL)
{
    usort($array, function($a, $b) use ($sort)
    {
        if ($a["ObjektTyp"] == $sort) {
            return -1;
        } else {
            return 1;
        }
    });
}

I would love to get some help with this, been pulling my hair all day.

Thank you very much!

  • 写回答

1条回答 默认 最新

  • douqianzha6213 2012-11-28 20:29
    关注

    First sort by numbers, then by the dates. This can be done by checking if the numbers are the same, and then sorting by dates.

    Something like this:

    function sort_by_type(&$array, $sort = NULL){
        usort($array, function($a, $b) use ($sort){
            if($a["ObjektTyp"] == $b["ObjektTyp"]){
                // already sorted by number, sort by date
                return strtotime($b['date']) - strtotime($a['date']); // sort descending
            }
            else{
                // sort by number
                if ($a["ObjektTyp"] == $sort) {
                    return -1;  // 2s to the top
                }
                elseif($b["ObjektTyp"] == $sort){
                   return 1;  // 2s to the top 
                }
                else {
                    return $a["ObjektTyp"] - $b["ObjektTyp"];
                }
            }
        });
    }
    

    DEMO: http://codepad.viper-7.com/3PMtmA

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

报告相同问题?

悬赏问题

  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题