我将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格式的日期信息,我希望能够以最近的日期作为第一行进行排序。


当前回答

下面是一个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'));

其他回答

“Usort”函数就是答案。 http://php.net/usort

可以使用usort函数对数组进行排序。

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

)

例子

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

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

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

It's reusable: you specify the sort column as a variable instead of hardcoding it. It's flexible: you can specify multiple sort columns (as many as you want) -- additional columns are used as tiebreakers between items that initially compare equal. It's reversible: you can specify that the sort should be reversed -- individually for each column. It's extensible: if the data set contains columns that cannot be compared in a "dumb" manner (e.g. date strings) you can also specify how to convert these items to a value that can be directly compared (e.g. a DateTime instance). It's associative if you want: this code takes care of sorting items, but you select the actual sort function (usort or uasort). Finally, it does not use array_multisort: while array_multisort is convenient, it depends on creating a projection of all your input data before sorting. This consumes time and memory and may be simply prohibitive if your data set is large.

的代码

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

如何使用

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

$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函数接受可变数量的参数,这些参数定义所需的排序,并返回一个函数,您应该将该函数用作usort或uasort的参数。

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

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

看到它的行动。

如果项是数字索引数组,则键也可以是数字。在问题中的例子中,这将是

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

看到它的行动。

多个排序列

您可以通过向make_comparer传递附加参数来指定多个排序列。例如,先按“number”排序,再按0索引列排序:

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

看到它的行动。

定制的预测

在某些情况下,您可能需要根据其值不适用于排序的列进行排序。样本数据集中的“birthday”列符合以下描述:将生日作为字符串进行比较是没有意义的(因为例如。“01/01/1980”出现在“10/10/1970”之前)。在本例中,我们希望指定如何将实际数据投影到可以直接与所需语义进行比较的表单。

投影可以指定为任何类型的可调用对象:字符串、数组或匿名函数。投影被假定接受一个参数并返回它的投影形式。

应该注意的是,虽然投影与usort和family使用的自定义比较函数类似,但它们更简单(只需要将一个值转换为另一个值),并且利用了make_comparer中已经包含的所有功能。

让我们在没有投影的情况下对示例数据集进行排序,看看会发生什么:

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

看到它的行动。

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

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

看到它的行动。

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

投影可以实现的事情还有很多。例如,获得不区分大小写排序的快速方法是使用strotolower作为投影。

也就是说,我还应该提到,如果您的数据集很大,最好不要使用投影:在这种情况下,在前面手动投影所有数据,然后不使用投影进行排序会更快,尽管这样做会以增加的内存使用换取更快的排序速度。

最后,下面是一个使用所有功能的示例:它首先按数字降序排序,然后按生日升序排序:

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

看到它的行动。

下面是一个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'));

使用闭包进行多行排序

下面是使用uasort()和匿名回调函数(闭包)的另一种方法。我经常使用这个函数。需要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' ) );