Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

sorting - questions on sort array by time in php

---array $points----

Array
    (
        [0] => Array
            (
                [0] => 2011-10-02 05:30:00
                [1] => 20
            )

        [1] => Array
            (
                [0] => 2011-10-04 09:30:00
                [1] => 12
            )

        [2] => Array
            (
                [0] => 2011-10-01 13:30:00
                [1] => 25
            )

        [3] => Array
            (
                [0] => 2011-10-03 02:30:00
                [1] => 31
            )

    )

I have an array at above and would like to sort this array by time. Then I used the code as following to sort and result is correct. However, if I changed the code time[$key] = $val[0] to $time = $val[0], the result is wrong.

Is there anyone can explain this to me? Many thanks!

foreach($points as $key=>$val){

        $time[$key] = $val[0];

        array_multisort($time, SORT_ASC, $points);
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

array_multisort sorts more than one array at once. However, it works on an array of columns, so the foreach loop is needed to get a column of the times. After building up this list, you can then perform the multisort. The $points array is ordered according to the indices in $times, as per this example in the docs.

However, you don't need to perform the sort inside the foreach, as that means the sort happens 4 times (in your example). It only needs to happen once:

foreach ($points as $key => $val) {
    $time[$key] = $val[0];
}

array_multisort($time, SORT_ASC, $points);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...