我如何sorting在PHP中的multidimensional array

我有CSV数据加载到一个multidimensional array。 这样每个“行”是一个logging,每个“列”包含相同types的数据。 我正在使用下面的函数来加载我的CSV文件。

function f_parse_csv($file, $longest, $delimiter) { $mdarray = array(); $file = fopen($file, "r"); while ($line = fgetcsv($file, $longest, $delimiter)) { array_push($mdarray, $line); } fclose($file); return $mdarray; } 

我需要能够指定一个列进行sorting,以便重新排列行。 其中一列包含格式为Ymd H:i:sdate信息,我希望能够sorting最近的date是第一行。

你可以使用array_multisort()

尝试这样的事情:

 foreach ($mdarray as $key => $row) { // replace 0 with the field's index/key $dates[$key] = $row[0]; } array_multisort($dates, SORT_DESC, $mdarray); 

对于PHP> = 5.5.0,只需提取列进行sorting即可。 不需要循环:

 array_multisort(array_column($mdarray, 0), SORT_DESC, $mdarray); 

介绍:PHP 5.3+的一个非常通用的解决scheme

我想在这里添加我自己的解决scheme,因为它提供了其他答案没有的function。

具体而言,该解决scheme的优点包括:

  1. 它是可重用的 :您将sorting列指定为variables而不是对其进行硬编码。
  2. 它很灵活 :您可以指定多个sorting列(尽可能多) – 额外的列用作最初比较相等的项目之间的tie tie。
  3. 这是可逆的 :你可以指定sorting应该颠倒 – 单独为每列。
  4. 它是可扩展的 :如果数据集包含无法以“哑”方式进行比较的列(例如datestring),则还可以指定如何将这些项目转换为可以直接比较的值(例如DateTime实例)。
  5. 如果你想要话,它是联想的 :这个代码负责sorting项目,但是select了实际的sortingfunction( usortuasort )。
  6. 最后,它不使用array_multisort :而array_multisort很方便,它依赖于在sorting之前创build所有input数据的投影。 这会消耗时间和内存,而且如果数据量很大,可能会让人望而却步。

代码

 function make_comparer() { // Normalize criteria up front so that the comparer finds everything tidy $criteria = func_get_args(); foreach ($criteria as $index => $criterion) { $criteria[$index] = is_array($criterion) ? array_pad($criterion, 3, null) : array($criterion, SORT_ASC, null); } return function($first, $second) use (&$criteria) { foreach ($criteria as $criterion) { // How will we compare this round? list($column, $sortOrder, $projection) = $criterion; $sortOrder = $sortOrder === SORT_DESC ? -1 : 1; // If a projection was defined project the values now if ($projection) { $lhs = call_user_func($projection, $first[$column]); $rhs = call_user_func($projection, $second[$column]); } else { $lhs = $first[$column]; $rhs = $second[$column]; } // Do the actual comparison; do not return if equal if ($lhs < $rhs) { return -1 * $sortOrder; } else if ($lhs > $rhs) { return 1 * $sortOrder; } } return 0; // tiebreakers exhausted, so $first == $second }; } 

如何使用

在本节中,我将提供对这个示例数据集进行sorting的链接:

 $data = array( array('zz', 'name' => 'Jack', 'number' => 22, 'birthday' => '12/03/1980'), array('xx', 'name' => 'Adam', 'number' => 16, 'birthday' => '01/12/1979'), array('aa', 'name' => 'Paul', 'number' => 16, 'birthday' => '03/11/1987'), array('cc', 'name' => 'Helen', 'number' => 44, 'birthday' => '24/06/1967'), ); 

基础

函数make_comparer接受可变数量的参数,这些参数定义了所需的sorting,并返回一个你应该用作usortuasort参数的uasort

最简单的用例是传入您想用来比较数据项的密钥。 例如,要按name项目对$data进行sorting,您可以执行此操作

 usort($data, make_comparer('name')); 

看到它的行动

如果项目是数字索引数组,则键也可以是数字。 对于这个问题的例子,这将是

 usort($data, make_comparer(0)); // 0 = first numerically indexed column 

看到它的行动

多个sorting列

您可以通过将其他parameter passing给make_comparer来指定多个sorting列。 例如,要按“编号”sorting,然后按零索引列sorting:

 usort($data, make_comparer('number', 0)); 

看到它的行动

高级function

如果将sorting列指定为数组而不是简单string,则可以使用更高级的function。 这个数组应该用数字索引,并且必须包含这些项目:

 0 => the column name to sort on (mandatory) 1 => either SORT_ASC or SORT_DESC (optional) 2 => a projection function (optional) 

让我们看看我们如何使用这些function。

反向sorting

按名称降序sorting:

 usort($data, make_comparer(['name', SORT_DESC])); 

看到它的行动

按数字降序sorting,然后按名称降序sorting:

 usort($data, make_comparer(['number', SORT_DESC], ['name', SORT_DESC])); 

看到它的行动

自定义投影

在某些情况下,您可能需要按值sorting的列进行sorting。 样本数据集中的“生日”栏符合以下描述:将生日作为string进行比较是没有意义的(因为例如“01/01/1980”在“10/10/1970”之前)。 在这种情况下,我们要指定如何将实际数据投影直接与所需语义进行比较的表单。

可以将投影指定为任何types的可调用对象 :string,数组或匿名函数。 假设投影接受一个参数并返回其投影forms。

应该注意的是,虽然预测与用于usort和family的自定义比较函数类似,但是它们更简单(只需要将一个值转换为另一个值),并利用已经存入make_comparer的所有function。

让我们对没有投影的示例数据集进行sorting,看看会发生什么:

 usort($data, make_comparer('birthday')); 

看到它的行动

那不是理想的结果。 但是我们可以使用date_create作为投影:

 usort($data, make_comparer(['birthday', SORT_ASC, 'date_create'])); 

看到它的行动

这是我们想要的正确顺序。

还有更多的东西可以预测。 例如,快速获取不区分大小写的sorting方法是使用strtolower作为投影。

也就是说,我还应该提到,如果数据集很大,最好不要使用预测:在这种情况下,将手动预览所有数据然后在不使用投影的情况下进行sorting会快得多,尽pipe这样做会交易增加内存使用率,以加快分类速度。

最后,这是一个使用所有function的示例:首先按数字降序sorting,然后按生日升序sorting:

 usort($data, make_comparer( ['number', SORT_DESC], ['birthday', SORT_ASC, 'date_create'] )); 

看到它的行动

随着usort 。 这是一个通用的解决scheme,您可以使用不同的列:

 class TableSorter { protected $column; function __construct($column) { $this->column = $column; } function sort($table) { usort($table, array($this, 'compare')); return $table; } function compare($a, $b) { if ($a[$this->column] == $b[$this->column]) { return 0; } return ($a[$this->column] < $b[$this->column]) ? -1 : 1; } } 

按第一列sorting:

 $sorter = new TableSorter(0); // sort by first column $mdarray = $sorter->sort($mdarray); 

多行使用闭包sorting

下面是使用uasort()和匿名callback函数(closure)的另一种方法。 我经常使用这个function。 PHP 5.3需要 – 没有更多的依赖!

 /** * Sorting array of associative arrays - multiple row sorting using a closure. * See also: http://the-art-of-web.com/php/sortarray/ * * @param array $data input-array * @param string|array $fields array-keys * @license Public Domain * @return array */ function sortArray( $data, $field ) { $field = (array) $field; uasort( $data, function($a, $b) use($field) { $retval = 0; foreach( $field as $fieldname ) { if( $retval == 0 ) $retval = strnatcmp( $a[$fieldname], $b[$fieldname] ); } return $retval; } ); return $data; } /* example */ $data = array( array( "firstname" => "Mary", "lastname" => "Johnson", "age" => 25 ), array( "firstname" => "Amanda", "lastname" => "Miller", "age" => 18 ), array( "firstname" => "James", "lastname" => "Brown", "age" => 31 ), array( "firstname" => "Patricia", "lastname" => "Williams", "age" => 7 ), array( "firstname" => "Michael", "lastname" => "Davis", "age" => 43 ), array( "firstname" => "Sarah", "lastname" => "Miller", "age" => 24 ), array( "firstname" => "Patrick", "lastname" => "Miller", "age" => 27 ) ); $data = sortArray( $data, 'age' ); $data = sortArray( $data, array( 'lastname', 'firstname' ) ); 

我知道这个问题已经过了两年了,但是这里有另一个函数来sorting一个二维数组。 它接受可变数量的参数,允许您传入多个键(即列名)进行sorting。 PHP 5.3需要。

 function sort_multi_array ($array, $key) { $keys = array(); for ($i=1;$i<func_num_args();$i++) { $keys[$i-1] = func_get_arg($i); } // create a custom search function to pass to usort $func = function ($a, $b) use ($keys) { for ($i=0;$i<count($keys);$i++) { if ($a[$keys[$i]] != $b[$keys[$i]]) { return ($a[$keys[$i]] < $b[$keys[$i]]) ? -1 : 1; } } return 0; }; usort($array, $func); return $array; } 

试试这里: http : //www.exorithm.com/algorithm/view/sort_multi_array

 function cmp($a, $b) { $p1 = $a['price']; $p2 = $b['price']; return (float)$p1 > (float)$p2; } uasort($my_array, "cmp"); 

http://qaify.com/sort-an-array-of-associative-arrays-by-value-of-given-key-in-php/

“Usort”function就是您的答案。
http://php.net/usort

这里是一个php4 / php5类,将sorting一个或多个字段:

 // a sorter class // php4 and php5 compatible class Sorter { var $sort_fields; var $backwards = false; var $numeric = false; function sort() { $args = func_get_args(); $array = $args[0]; if (!$array) return array(); $this->sort_fields = array_slice($args, 1); if (!$this->sort_fields) return $array(); if ($this->numeric) { usort($array, array($this, 'numericCompare')); } else { usort($array, array($this, 'stringCompare')); } return $array; } function numericCompare($a, $b) { foreach($this->sort_fields as $sort_field) { if ($a[$sort_field] == $b[$sort_field]) { continue; } return ($a[$sort_field] < $b[$sort_field]) ? ($this->backwards ? 1 : -1) : ($this->backwards ? -1 : 1); } return 0; } function stringCompare($a, $b) { foreach($this->sort_fields as $sort_field) { $cmp_result = strcasecmp($a[$sort_field], $b[$sort_field]); if ($cmp_result == 0) continue; return ($this->backwards ? -$cmp_result : $cmp_result); } return 0; } } ///////////////////// // usage examples // some starting data $start_data = array( array('first_name' => 'John', 'last_name' => 'Smith', 'age' => 10), array('first_name' => 'Joe', 'last_name' => 'Smith', 'age' => 11), array('first_name' => 'Jake', 'last_name' => 'Xample', 'age' => 9), ); // sort by last_name, then first_name $sorter = new Sorter(); print_r($sorter->sort($start_data, 'last_name', 'first_name')); // sort by first_name, then last_name $sorter = new Sorter(); print_r($sorter->sort($start_data, 'first_name', 'last_name')); // sort by last_name, then first_name (backwards) $sorter = new Sorter(); $sorter->backwards = true; print_r($sorter->sort($start_data, 'last_name', 'first_name')); // sort numerically by age $sorter = new Sorter(); $sorter->numeric = true; print_r($sorter->sort($start_data, 'age')); 

在我能得到TableSorter类运行之前,我已经提出了一个基于Shinhan提供的函数。

 function sort2d_bycolumn($array, $column, $method, $has_header) { if ($has_header) $header = array_shift($array); foreach ($array as $key => $row) { $narray[$key] = $row[$column]; } array_multisort($narray, $method, $array); if ($has_header) array_unshift($array, $header); return $array; } 
  • $ array是您要sorting的MD Array。
  • $列是你想sorting的列。
  • $方法就是你想要执行的sorting,比如SORT_DESC
  • 如果第一行包含您不想sorting的标题值,则$ has_header被设置为true。

我尝试了几个stream行的array_multisort()和usort()答案,他们都没有为我工作。 数据只是混乱,代码是不可读的。 这是一个肮脏的解决scheme。 警告:只有当你确定一个stream氓分隔符不会再回来困扰你时,才使用它!

假设您的多个数组中的每行都如下所示:name,stuff1,stuff2:

 // Sort by name, pull the other stuff along for the ride foreach ($names_stuff as $name_stuff) { // To sort by stuff1, that would be first in the contatenation $sorted_names[] = $name_stuff[0] .','. name_stuff[1] .','. $name_stuff[2]; } sort($sorted_names, SORT_STRING); 

需要按字母顺序回来吗?

 foreach ($sorted_names as $sorted_name) { $name_stuff = explode(',',$sorted_name); // use your $name_stuff[0] // use your $name_stuff[1] // ... } 

是的,它很脏。 但超级容易,不会让你的头部爆炸。

我更喜欢使用array_multisort。 请参阅这里的文档。