-1

我有以下格式的数组:

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 排序方法的内容,但我不知道最好的解决方案是什么。

任何帮助表示赞赏,

4

2 回答 2

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);

此外,您输入数据的结构似乎有点奇怪。额外的级别并不是真正需要的,并且不必要地使事情复杂化。

于 2012-04-28T17:04:31.153 回答
1
uasort($array, 'cmp');

function cmp($a, $b)
{
    if (key($a) == key($b)) {
        return 0;
    }
    return (key($a) < key($b)) ? -1 : 1;
}
于 2012-04-28T17:08:15.840 回答