回覆列表
  • 1 # 網站設計

    主要用到的PHP函式 array_multisort()

    1.先實現指定多維陣列一個欄位排序根據二維陣列的id值來排序,轉換後的陣列格式如下:

    function arraySortByOneField($data, $field, $sort = SORT_DESC)

    {

      $field = array_column($data, $field);

      array_multisort($field,$sort,$data);

      return $data;

    }

    $data = array(0=>array("id"=>7, "name"=>"Apple", "age"=> 18),1=>array("id"=>8, "name"=>"Bed", "age"=>17),2=>array("id"=>6, "name"=>"Cos", "age"=>16),3=>array("id"=>5, "name"=>"Cos", "age"=>14));

    $newArray = arraySortByOneField($data, "id", SORT_DESC);

    var_dump($newArray );

    2.實現多維陣列的指定兩個欄位排序根據二維陣列的多個屬性值來排序,轉換後的陣列格式如下:

    function sortArrByManyField()

    {

      $args = func_get_args();

      if(empty($args)){

        return null;

      }

      $arr = array_shift($args);

      if(!is_array($arr)){

        throw new Exception("第一個引數不為陣列");

      }

      foreach($args as $key => $field){

        if(is_string($field)){

          $temp = array();

          foreach($arr as $index=> $val){

            $temp[$index] = $val[$field];

          }

          $args[$key] = $temp;

        }

      }

      $args[] = &$arr;//引用值

      call_user_func_array("array_multisort",$args);

      return array_pop($args);

    }

    $data = array(0=>array("id"=>7, "name"=>"Apple", "age"=> 18),1=>array("id"=>8, "name"=>"Bed", "age"=>17),2=>array("id"=>6, "name"=>"Cos", "age"=>16),3=>array("id"=>5, "name"=>"Cos", "age"=>14));

    $newArray = arraySortByManyField($data, "id", SORT_ASC, "name", SORT_ASC, "age", SORT_DESC);

    var_dump($newArray );

  • 2 # 程式設計師tb

    PHP的自定義排序吧,好幾個函式呢,具體看下官方文件,講的很詳細: https://www.php.net/manual/zh/array.sorting.php

  • 中秋節和大豐收的關聯?
  • 公司公章財務章營業執照全部丟失了能補辦嗎?如何補辦?