PHP基于多个键值对多维数组进行排序

时间:2014-03-17 16:20:47

标签: php

我想根据'距离'对多维数组进行排序。价值。如果距离相等,那么我必须比较“创造”的价值。 date然后是价格,最后是字母顺序。我可以根据不同的键值对数组进行排序。

$ array = array(0 => array(' title' =>' title1',' distance' => 200,&#39 ; date' =>' 2014-16',' price' => 12),1 =>数组('标题' => ' title2','距离' => 100,' date' =>' 014-03-15','价' = GT; 17));

数组看起来像这样。优先考虑的是日期等等

1 个答案:

答案 0 :(得分:1)

我为这个问题写了一个函数,

结帐我的要点:
https://gist.github.com/chazmead/8829079

<?php
/**
 * 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;
    });
}

这可以这样使用:

$array = array( 0 => array('title'=>'title1', 'distance'=>200, 'date'=>'2014-03-16','price'=>12), 1 => array('title'=>'title2', 'distances'=>100, 'date'=>'014-03-15','price'=>17), );

$order = array('distance' => SORT_ASC, 'created' => SORT_ASC, 'title' => SORT_ASC);

multisort($array,$order);