簡體   English   中英

PHP基於多個鍵值對多維數組進行排序

[英]PHP Sorting of mutidimensional array based on more than one key values

我想基於``距離''值對多維數組進行排序。如果距離相等,則我必須比較``創建''日期,價格和最后的字母順序。我可以根據不同的鍵值對數組進行排序。

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

數組看起來像這樣。首先是距離優先,然后是日期等等

我為這個確切的東西寫了一個函數,

結帳我的要旨:
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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM