Sample code for PHP multidimensional array to specify multi field sorting

  • 2021-10-13 06:47:54
  • OfStack

Introduction of array_multisort method

array_multisort-Sorts multiple arrays or multidimensional arrays. The instructions in the php manual are as follows:

bool array_multisort ( array &$arr [, mixed $arg = SORT_ASC [, mixed $arg = SORT_REGULAR [, mixed $... ]]] )

Parameter

arr
1 array to sort.

arg
Each of the next parameters can be another array or a sort flag option parameter for the previous array: SORT_ASC, SORT_DESC, SORT_REGULAR, SORT_NUMERIC, SORT_STRING.

Additional arg's.

First, realize the sorting of one field in the specified multidimensional array

It is required to sort the array according to one of the fields, and the array assumes the following:


  $array = array(
      0=>array('id'=>8,'name'=>'Tom'),
      1=>array('id'=>9,'name'=>'Peter'),
      2=>array('id'=>5,'name'=>'Jack')
  );

We want to sort according to the id value of the 2-dimensional array, and the converted array format is as follows:


  $array = array(
      0=>array('id'=>5,'name'=>'Jack')
      1=>array('id'=>8,'name'=>'Tom'),
      2=>array('id'=>9,'name'=>'Peter')
  );

To complete the above transformation, you need to use the array_multisort function described above, as follows:


  function sortArrByOneField(&$array, $field, $desc = false){
    $fieldArr = array();
    foreach ($array as $k => $v) {
     $fieldArr[$k] = $v[$field];
    }
    $sort = $desc == false ? SORT_ASC : SORT_DESC;
    array_multisort($fieldArr, $sort, $array);
  }

Participate in sorting in passing array_multisort by saving the $field of each array of arrays to be sorted in the 1-bit group fieldArr. Where the values of the field array are as follows:


array(0=>8,1=>9,2=>5)

After passing in array_multisort, it is equivalent to sorting the $field1 dimension array, and then reconstructing the passed-in array to be sorted according to the sorted key.

Realize the sorting of specified multiple fields in multidimensional arrays

The above example shows how to implement a multidimensional array that specifies one field to sort, but what to think about if you want to implement a multidimensional array that specifies multiple fields to sort an array?
How many fields are there? 2, 3 or more, so this uncertain factor needs to be eliminated.

Let's first look at the scheme of 2 specifying 2 fields for sorting:


  $arr = array(
    '0' => array(
      'id' => 3,
      'age' => 27 
    ),
    '1' => array(
      'id' => 5,
      'age' => 50
    ) , 
    '2' => array(
      'id' => 4,
      'age' => 44
    ),
    '3' => array(
      'id' => 3,
      'age' => 78
    ) 
  );
  foreach ( $arr as $key => $row ){
    $id[$key] = $row ['id'];
    $age[$key] = $row ['age'];
  }
  array_multisort($id, SORT_ASC, $age, SORT_DESC, $arr);
  print_r($arr);
  //result:Array([0]=>Array(['id']=>3 ['age']=>78) [1]=>Array(['id']=>3 ['age']=>27) [2]=>Array(['id']=>4 ['age']=>44) [3]=>Array(['id']=>5 ['age']=>50))

By reconstructing the above code, the incoming value can be obtained dynamically by using func_get_args function in php, which can solve the problem of uncertain number of multiple fields. The implementation is as follows:


  $array1 = array(
        0=>array('id'=>8,'name'=>'Apple','age'=> 18),
        1=>array('id'=>8,'name'=>'Bed','age'=>17),
        2=>array('id'=>5,'name'=>'Cos','age'=>16),
        3=>array('id'=>5,'name'=>'Cos','age'=>14)
  );
  function sortArrByManyField(){
    $args = func_get_args();
    if(empty($args)){
      return null;
    }
    $arr = array_shift($args);
    if(!is_array($arr)){
      throw new Exception(" No. 1 1 Parameters are not arrays ");
    }
    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;// Reference value 
    call_user_func_array('array_multisort',$args);
    return array_pop($args);
  }
  $arr = sortArrByManyField($array1,'id',SORT_ASC,'name',SORT_ASC,'age',SORT_DESC);
  print_r($arr);

The running results are as follows:

array(4) {
[0]= > array(3) {
["id"]= > int(5)
["name"]= > string(3) "Cos"
["age"]= > int(16)
}
[1]= > array(3) {
["id"]= > int(5)
["name"]= > string(3) "Cos"
["age"]= > int(14)
}
[2]= > array(3) {
["id"]= > int(8)
["name"]= > string(5) "Apple"
["age"]= > int(18)
}
[3]= > array(3) {
["id"]= > int(8)
["name"]= > string(3) "Bed"
["age"]= > int(17)
}
}


Related articles: