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

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

报告相同问题?