【问题标题】:sort array of arrays in php [duplicate]在php中对数组进行排序[重复]
【发布时间】:2013-03-22 19:10:34
【问题描述】:

我有一个这样创建的数组:

$i = 0;

$files = array();   

while ($file = mysql_fetch_array($query_files)) {
    $files[$i] = array();
    $files[$i] = $file;
    $i++;
}

我需要能够根据每个 $file['name'] aka $files[$i]['name'] 对 $files 数组进行排序。

我该怎么做? 谢谢!

【问题讨论】:

标签: php mysql arrays sorting


【解决方案1】:

ORDER BY NAME 添加到您的查询中。严重地。这是最快、最安全、最安全的方法。我不是在开玩笑。此外,您会告诉数据库做一些它擅长的事情,而 PHP 只能做这件事。最后,您可以选择索引数据库的名称列,而 PHP 不提供索引。

如果你绝对必须自己排序,那么你需要使用usort

// this example is almost a clone of something in the docs.
function cmp($a, $b)
{
    return strcmp($a["name"], $b["name"]);
}
usort($files, "cmp");

【讨论】:

    【解决方案2】:

    看起来像是 usort 的工作

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-02
      • 2010-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-22
      • 1970-01-01
      相关资源
      最近更新 更多