Help me sort this php array using usort()

╄→尐↘猪︶ㄣ 提交于 2019-12-24 00:24:30

问题


I have a data structure that looks like

Array
(
[0] => Array
    (
        [0] => something
        [1] => 1296986500
    )

[1] => Array
    (
        [0] => something else
        [1] => 1296600100
    )

[2] => Array
    (
        [0] => another thing
        [1] => 1296831265
    )
)

I'm trying to sort the array based off of the integer which is a unix timestamp. The following function looks right to me but is not sorting the way I want.

function cmp($a, $b)
{
    if ($a[1] == $b[1]) {
        return 0;
    }
    return ($a[1] < $b[1]) ? -1 : 1;
}

NOTE when calling this function within a class the OO syntax is the following

uasort($_data, array($this, 'cmp'));

回答1:


That sorts your timestamps in ascending order; for descending order, flip the second comparison (i.e. change $a[1] < $b[1] to $a[1] > $b[1]):

function cmp($a, $b)
{
    if ($a[1] == $b[1]) {
        return 0;
    }
    return ($a[1] > $b[1]) ? -1 : 1;
}



回答2:


You can setup time stamp as pivot. And use array_multisort().

<?php
// Obtain a list of columns
foreach ($data as $key => $row) {
    $time[$key]  = $row[1]; //unix timestamp 
}


array_multisort( $time, SORT_ASC, $data);
?> 


来源:https://stackoverflow.com/questions/4911291/help-me-sort-this-php-array-using-usort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!