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 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 spring后端vue前端
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题