Search code examples
phparraysarray-multisort

php array_multisort use array name as argument


Sorry if this is duplicate, I have tried to look at previous posts, but maybe my limited understanding of php gets in the way.

This works to sort arrays 1 and 3 by array 2:

<?php

$ar[1] = array("game","scissors","rock","paper");
$ar[2] = array("D", "B", "A", "C");
$ar[3] =array("four","two","one","three");

array_multisort($ar[2],$ar[1],$ar[3]);

for ($j=0;$j<=3;$j++) {

    for ($i=1;$i<=3;$i++) {
  echo $ar[$i][$j]." ";
}
echo "\n";
}

?>

output:

rock A one
scissors B two
paper C three
game D four

Fine. But I want the list of arrays used as argument for array_multisort() to be specified by user input, so it can't be literal. Instead, I would like the program to decide the order of arrays in the list based on the user input and then name the resulting array of arrays $supar (superarray). But when using $supar as argument for array_multisort(), no sorting is carried out.

<?php

$ar[1] = array("game","scissors","rock","paper");
$ar[2] = array("D", "B", "A", "C");
$ar[3] =array("four","two","one","three");


$supar = array($ar[2],$ar[1],$ar[3]);
array_multisort($supar);

for ($j=0;$j<=3;$j++) {

    for ($i=1;$i<=3;$i++) {
  echo $ar[$i][$j]." ";
}
echo "\n";
}

?>

Output:

game D four
scissors B two
rock A one
paper C three

How should I do to make array_multisort() sort the arrays in $supar by a specified $ar array?

Thank you for your patience.


Solution

  • You can call array_multisort() (or any other function) without specifying its arguments explicitly if you have the arguments in an array by using call_user_func_array().

    array_multisort() gets its arguments by reference (in order to be able to modify them). You have to consider this when you build the array you use as argument to call_user_func_array() and put references in this array:

    // Input arrays
    $ar[1] = array("game", "scissors", "rock", "paper");
    $ar[2] = array("D", "B", "A", "C");
    $ar[3] = array("four", "two", "one", "three");
    
    // Build the list of arguments for array_multisort()
    // Use references to the arrays you want it to sort
    $supar = array(&$ar[2], &$ar[1], &$ar[3]);
    
    // Call array_multisort() indirectly
    // This is the same as array_multisort($ar[2], $ar[1], $ar[3]);
    call_user_func_array('array_multisort', $supar);
    

    Check it in action: https://3v4l.org/ptiog