PHP - Multi-Sorting with array_multisort()

Introduction

array_multisort() sorts multiple related arrays at the same time, preserving the relationship between the arrays.

To use it, simply pass in a list of all the arrays you want to sort:

array_multisort($array1, $array2,...);

By passing all three arrays to array_multisort(), the arrays are all sorted according to the values in the first array:

Demo

<?php
$authors = array("D","A","B","C");
$titles = array("Java","Database","Json","MySQL");
$pubYears = array(2018, 2017, 2018, 1859);

array_multisort($authors, $titles, $pubYears);
print_r ($authors);/*  w  w w  .  java 2s  .  c  o m*/
echo"\n";
print_r ($titles);
echo"\n";
print_r ($pubYears);
?>

Result

To sort by title instead, just change the order of the arguments passed to array_multisort():

array_multisort($titles, $authors, $pubYears);

array_multisort() sorts by the values in the first array, then by the values in the next array, and so on. Consider this example:

Demo

<?php
$authors = array("A","B","A","C","A","D");

$titles = array("Java","Database","SQL","Json","Javascript","MySQL");

$pubYears = array(2018, 2017, 2018, 2018, 2017, 1859);

array_multisort($authors, $titles, $pubYears);

print_r ($authors);//  w  ww .  j  ava  2s .c  om
echo"\n";

print_r ($titles);
echo"\n";

print_r ($pubYears);
?>

Result

Related Topic