In depth analysis of PHP array_multisort of functions

  • 2020-06-15 07:54:32
  • OfStack

1. Look at the simplest case first. There are two arrays:
$arr1 = array(1,9,5);
$arr2 = array(6,2,4);
array_multisort($arr1,$arr2);
print_r ($arr1); // I get 1,5,9
print_r ($arr2); // I get 6,4,2
I estimate that the values of the two arrays are always the same: 1 for 6,9 for 2,5 for 4.
Let's add one more array and see what happens:
$arr1 = array(1,9,5);
$arr2 = array(6,2,4);
$arr3 = array(3,7,8);
array_multisort($arr1,$arr2,$arr3);
If you look at the results, one corresponds to six all the way to three, and so do the other terms. This correspondence is referred to in the manual as "preserving the original key name association when sorting".
Alternatively, you can think of each array as a column in a database table. The corresponding 1,6,3 are 1 data rows, 9,2,7 are another 1 data rows...
array_multisort first sorts by the first array (think of it as a column), then by the second array (column) if the first array (column) has the same value.
Specifically, the following program can be used to test:
$arr1 = array(1,9,5,9);
$arr2 = array(6,2,4,1);
$arr3 = array(3,7,8,0);
array_multisort($arr1,$arr2,$arr3);
You can imagine that the result of $arr3 here is (3,8,0,7).

2. Next, the parameters of array_multisort are explained. The parameters of this function are flexible. The simplest case is one or n array as shown above. Note that the number of items in each array should be 1, otherwise warning will invalidate the sorting.
Like this array_multisort ($arr1, $arr2, $arr3); The default is that all arrays are sorted in ascending order. If you want to compare $arr2 in descending order as a string, write:
array_multisort($arr1, $arr2, SORT_DESC, SORT_STRING, $arr3);
Each array can be followed by a sort order flag, a sort type flag, or both. But each sort flag can only appear one after each array.
Details are as follows:
Sorting order flag:
SORT_ASC - Sort in ascending order (default)
SORT_DESC - sorted in descending order
Sort type flag:
SORT_REGULAR - Compare items as usual (default)
SORT_NUMERIC - Compares items by value
SORT_STRING - Compares items by string

3. Finally, what is array_multisort actually used for?
We usually have 1 number of multidimensional arrays to sort:


$guys = Array
(
    [0] => Array
        (
 [name] => jake
 [score] => 80
 [grade] => A
        )
    [1] => Array
        (
 [name] => jin
 [score] => 70
 [grade] => A
        )
    [2] => Array
        (
 [name] => john
 [score] => 80
 [grade] => A
        )
    [3] => Array
        (
 [name] => ben
 [score] => 20
 [grade] => B
        )
)

For example, if we want to rank grades in reverse order, we can rank grades in ascending order by name if they are the same.
Then we need to get two more arrays in the order of $guys:
$scores = array(80,70,80,20);
$names = array('jake','jin','john','ben');
then
array_multisort ($scores SORT_DESC, $names, $guys); We have to do is
Could you be a little bit more flexible, and every time you want to sort, you have to get some other array out?
In fact, qeephp's helper_array class has been well encapsulated, here are its two methods, the need to modify 1 can be used:

/**
*  Sorts the array by the specified key 
*
*  Usage: 
* @code php
* $rows = array(
*array('id' => 1, 'value' => '1-1', 'parent' => 1),
*array('id' => 2, 'value' => '2-1', 'parent' => 1),
*array('id' => 3, 'value' => '3-1', 'parent' => 1),
*array('id' => 4, 'value' => '4-1', 'parent' => 2),
*array('id' => 5, 'value' => '5-1', 'parent' => 2),
*array('id' => 6, 'value' => '6-1', 'parent' => 3),
* );
*
* $rows = Helper_Array::sortByCol($rows, 'id', SORT_DESC);
* dump($rows);
* //  The output result is: 
* // array(
* //         array('id' => 6, 'value' => '6-1', 'parent' => 3),
* //         array('id' => 5, 'value' => '5-1', 'parent' => 2),
* //         array('id' => 4, 'value' => '4-1', 'parent' => 2),
* //         array('id' => 3, 'value' => '3-1', 'parent' => 1),
* //         array('id' => 2, 'value' => '2-1', 'parent' => 1),
* //         array('id' => 1, 'value' => '1-1', 'parent' => 1),
* // )
* @endcode
*
* @param array $array  The array to sort 
* @param string $keyname  The sort of key 
* @param int $dir  Sort direction 
*
* @return array  Sorted array 
*/
          static function sortByCol($array, $keyname, $dir = SORT_ASC)
          {
   return self::sortByMultiCols($array, array($keyname => $dir));
          }
          /**
*  will 1 a 2 Dimensional arrays are sorted by columns, similarly  SQL  In the statement  ORDER BY
*
*  Usage: 
* @code php
* $rows = Helper_Array::sortByMultiCols($rows, array(
*'parent' => SORT_ASC, 
*'name' => SORT_DESC,
* ));
* @endcode
*
* @param array $rowset  The array to sort 
* @param array $args  The sort of key 
*
* @return array  Sorted array 
*/
          static function sortByMultiCols($rowset, $args)
          {
   $sortArray = array();
   $sortRule = '';
   foreach ($args as $sortField => $sortDir) 
   {
       foreach ($rowset as $offset => $row) 
       {
$sortArray[$sortField][$offset] = $row[$sortField];
       }
       $sortRule .= '$sortArray[\'' . $sortField . '\'], ' . $sortDir . ', ';
   }
   if (empty($sortArray) || empty($sortRule)) { return $rowset; }
   eval('array_multisort(' . $sortRule . '$rowset);');
   return $rowset;
          }


Related articles: