Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在PHP中对多维数组排序_Php_Sorting_Multidimensional Array - Fatal编程技术网

如何在PHP中对多维数组排序

如何在PHP中对多维数组排序,php,sorting,multidimensional-array,Php,Sorting,Multidimensional Array,我将CSV数据加载到多维数组中。这样,每个“行”都是一条记录,每个“列”都包含相同类型的数据。我正在使用下面的函数加载我的CSV文件 function f_parse_csv($file, $longest, $delimiter) { $mdarray = array(); $file = fopen($file, "r"); while ($line = fgetcsv($file, $longest, $delimiter)) { array_push($md

我将CSV数据加载到多维数组中。这样,每个“行”都是一条记录,每个“列”都包含相同类型的数据。我正在使用下面的函数加载我的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;
}
我需要能够指定要排序的列,以便它重新排列行。其中一列包含日期信息,格式为
Y-m-d H:i:s
,我希望能够以最新日期作为第一行进行排序。

您的答案是“Usort”函数。

使用。以下是一个通用解决方案,可用于不同的列:

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

我更喜欢使用array\u 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,只需提取要排序的列。不需要循环:

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

下面是一个php4/php5类,它将对一个或多个字段进行排序:

// 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'));
//分类器类
//php4和php5兼容
分类机{
var$sort_字段;
var$backwards=false;
var$numeric=false;
函数排序(){
$args=func_get_args();
$array=$args[0];
if(!$array)返回数组();
$this->sort\u fields=array\u slice($args,1);
如果(!$this->sort_fields)返回$array();
如果($this->numeric){
usort($array,array($this,'numericCompare'));
}否则{
usort($array,array($this,'stringCompare'));
}
返回$array;
}
函数数值比较($a,$b){
foreach($this->sort\u字段作为$sort\u字段){
如果($a[$sort\u字段]=$b[$sort\u字段]){
继续;
}
返回($a[$sort\u字段]<$b[$sort\u字段])?($this->backwards-1:-1):($this->backwards-1:1);
}
返回0;
}
函数stringCompare($a,$b){
foreach($this->sort\u字段作为$sort\u字段){
$cmp_result=strcasecmp($a[$sort_字段],$b[$sort_字段]);
如果($cmp_result==0)继续;
返回($this->backwards?-$cmp\u result:$cmp\u result);
}
返回0;
}
}
/////////////////////
//用法示例
//一些起始数据
$start\u data=array(
数组('first\u name'=>'John','last\u name'=>'Smith','age'=>10),
数组('first\u name'=>'Joe','last\u name'=>'Smith','age'=>11),
数组('first\u name'=>'Jake','last\u name'=>'Xample','age'=>9),
);
//按姓排序,然后按名排序
$sorter=新分拣机();
打印($sorter->sort($start_data,'last_name','first_name'));
//按名字排序,然后按姓氏排序
$sorter=新分拣机();
打印($sorter->sort($start_data,'first_name','last_name'));
//按姓氏排序,然后按姓氏排序(向后)
$sorter=新分拣机();
$sorter->backwards=true;
打印($sorter->sort($start_data,'last_name','first_name'));
//按年龄按数字排序
$sorter=新分拣机();
$sorter->numeric=true;
打印($sorter->sort($start_data,'age'));

在运行TableSorter类之前,我已经根据所提供的功能想出了一个函数

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是要排序的MD数组
  • $column是要按其排序的列
  • $method是您希望执行排序的方式,例如sort_DESC
  • 如果第一行包含您不希望排序的标题值,$has_header设置为true

我知道这个问题已经有两年没有被问到和回答了,但这里有另一个对二维数组排序的函数。它接受数量可变的参数,允许您传入多个键(即列名)进行排序。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;
}
函数排序多数组($array,$key)
{
$keys=array();
对于($i=1;$i使用闭包进行多行排序
这里是使用uasort()和匿名回调函数(closure)的另一种方法。我经常使用该函数。PHP5.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' ) );
简介:一个非常通用的PHP5.3解决方案+ 我想在这里添加我自己的解决方案,因为它提供了其他答案所没有的功能

具体而言,此解决方案的优点包括:

  • 它是可重用的:您可以将排序列指定为变量,而不是硬编码
  • 它的灵活性:您可以指定多个排序列(任意多个)--附加列用作初始比较相等的项目之间的分段符
  • 它是可逆的:您可以指定排序应该是反向的——每个列单独进行排序
  • 它是可扩展的:如果数据集包含无法以“哑”方式进行比较的列(例如日期字符串),您还可以指定如何将这些项转换为可直接比较的值(例如
    DateTime
    实例)
  • 如果需要,它是关联的:此代码负责对项目进行排序,但您可以选择实际的排序功能(
    usort
    uasort
  • 最后,它不使用
    array\u multisort
    :虽然
    array\u multisort
    很方便,但它依赖于在排序之前创建所有输入数据的投影。这会消耗时间和内存,如果数据集太大,可能根本无法使用
  • 代码 基础 函数
    make\u comparer
    接受数量可变的参数,这些参数定义了所需的排序,并返回一个函数,该函数应该用作
    usort
    uasort
    的参数

    最简单的用例是传入您希望用于比较数据项的键。例如,按您要执行的
    名称
    项对
    $data
    进行排序

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

    如果项是数字索引数组,则键也可以是数字

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

    多个排序列 您可以通过向
    make\u comparer
    传递附加参数来指定多个排序列。例如,按“编号”排序,然后按零索引列排序:

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

    高级功能
    usort($data, make_comparer('name'));
    
    usort($data, make_comparer(0)); // 0 = first numerically indexed column
    
    usort($data, make_comparer('number', 0));
    
    0 => the column name to sort on (mandatory)
    1 => either SORT_ASC or SORT_DESC (optional)
    2 => a projection function (optional)
    
    usort($data, make_comparer(['name', SORT_DESC]));
    
    usort($data, make_comparer(['number', SORT_DESC], ['name', SORT_DESC]));
    
    usort($data, make_comparer('birthday'));
    
    usort($data, make_comparer(['birthday', SORT_ASC, 'date_create']));
    
    usort($data, make_comparer(
        ['number', SORT_DESC],
        ['birthday', SORT_ASC, 'date_create']
    ));
    
    // 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 = array(
      array('price'=>'1000.50','product'=>'product 1'),
      array('price'=>'8800.50','product'=>'product 2'),
      array('price'=>'200.0','product'=>'product 3')
    );
    
    function cmp($a, $b) {
      return $a['price'] > $b['price'];
    }
    usort($array, "cmp");
    print_r($array);
    
    Array
    (
        [0] => Array
            (
                [price] => 134.50
                [product] => product 1
            )
    
        [1] => Array
            (
                [price] => 2033.0
                [product] => product 3
            )
    
        [2] => Array
            (
                [price] => 8340.50
                [product] => product 2
            )
    
    )