在多维数组中排序



我有一个像这样的数组

Array
(
    [A] => Array
        (
            [0] => 1
            [1] => XYZ
        )
    [B] => Array
        (
            [0] => 2
            [1] => ABC
        )
    [C] => Array
        (
            [0] => 0
            [1] => DEF
        )
    [D] => Array
        (
            [0] => 3
            [1] => GHI
        )
    [E] => Array
        (
            [0] => 0
            [1] => JKL
        )
)

我想根据第0个位置的数字值对这个数组进行排序。有人能帮我解决这个问题吗?

使用ussort自定义排序方法。http://nl1.php.net/manual/en/function.usort.php

<?php
function cmp($a, $b)
{
    if ($a[0] == $b[0]) {
        return 0;
    }
    return ($a[0] < $b[0]) ? -1 : 1;
}
// your array
$a = array( 
    'a' => array(0 => 1, 1 => 'XYZ'), 
    'b' => array(0 => 0, 1 => 'ABC')
);
usort($a, "cmp");

我已经为这个确切的目的做了一个基于ussort的函数,所以我想我不会和你分享:)

/**
 * Sort a 2 dimension array with values in the second dimension
 *
 * Developer: chazmead89@gmail.com  // @RaggaMuffin-4201
 * 
 * Order can be string of a field, which will default to asc
 * OR as array(field1,field2...fieldn) each defaulting to asc
 * OR as assoc array(field1 => dir[asc|desc], field2 => dir[asc|desc]...fieldn
 * => dir[asc|desc])
 *
 * PHP Sort constants can be used: SORT_ASC | SORT_DESC
 *
 * @param array $array array to sort - passed by reference
 * @param mixed $order
 * @return null
 */
function multisort(&$array,$order) {
    usort($array, function($a,$b) use ($order) {
      $sortMap = array('asc'=>SORT_ASC,'desc'=>SORT_DESC);
      $aObj = (object)$a;
      $bObj = (object)$b;
      if (is_string($order))
        $order = array($order);
      if (is_object($order))
        $order = (array)$order;
      $i = 0;
      $cOrder = count($order);
      foreach($order as $field => $dir) {
        if (is_numeric($field)) {
          $field = $dir;
          $dir = SORT_ASC;
        }
        // Goto next step when a mis-match is found.
        if ($aObj->$field != $bObj->$field)
          break;
        // All fields match return 0
        if (++$i === $cOrder)
          return 0;
      }
      if(!is_numeric($dir)) {
        $dir = strtolower($dir);
        $dir = $sortMap[$dir];
      }
      $d = ($dir === SORT_DESC) ? -1 : 1;
      $c = ($aObj->$field < $bObj->$field) ? -1 : 1;
      return $c*$d;
    });
}

这里是Gist: https://gist.github.com/chazmead/8829079

相关内容

  • 没有找到相关文章

最新更新