在时间戳上排序数组

时间:2012-04-28 17:01:08

标签: php arrays sorting timestamp

我有一个以下格式的数组:

array
  0 => 
    array
      1335541286 => 
        array
          'event' => string 'track' (length=5)
          'title' => string 'Plastic Humans' (length=14)
          'album' => string 'Cities of hunger' (length=16)
          'artist' => string 'The Maple Room' (length=14)
  1 => 
    array
      1335540999 => 
        array
          'event' => string 'track' (length=5)
          'title' => string 'Atlantis' (length=8)
          'album' => string 'Cities of hunger' (length=16)
          'artist' => string 'The Maple Room' (length=14)
  2 => 
    array
      1335540064 => 
        array
          'event' => string 'track' (length=5)
          'title' => string 'Doradus Stars' (length=13)
          'album' => string 'A Glimpse of the Inside' (length=23)
          'artist' => string 'The Maple Room' (length=14)
  3 => 
    array
      1335539855 => 
        array
          'event' => string 'track' (length=5)
          'title' => string 'In Twenty Five' (length=14)
          'album' => string 'A Glimpse of the Inside' (length=23)
          'artist' => string 'The Maple Room' (length=14)
  4 => 
    array
      1334016000 => 
        array
          'event' => string 'purchase' (length=8)
          'title' => string 'Donald Trump - Single' (length=21)
          'artist' => string 'Mac Miller' (length=10)
          'format' => string '10"' (length=3)

我希望根据密钥(即时间戳)对数组进行排序。我已经阅读了很多关于PHP排序方法的内容,但我无法弄清楚最佳解决方案是什么。

感谢任何帮助,

2 个答案:

答案 0 :(得分:1)

使用缩小数据:

$data = array(
  array('1335541286' => array('1')),
  array('1335540999' => array('1')),
  array('1335540064' => array('1')),
);

usort($data, function ($a, $b) {
  return key($a) - key($b);
});

print_r($data);

输入数据的结构也有点奇怪。额外的水平并不是真正需要的,并且不必要地使问题复杂化。

答案 1 :(得分:1)

uasort($array, 'cmp');

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