views:

961

answers:

1

Hi,

I have a multi-dimensional array, which basically consists of one sub-array for each year. So, for example, if I had three year's worth of data, it might look like this:

$data[0] = Array(0,1,2,3,4,5,6,7);
$data[1] = Array(6,5,4,3,6,7,8,9);
$data[2] = Array(1,4,2,5,7,3,1,4);

Now I want to be able to sort those arrays on the basis of one of the years. E.g., I might want to sort based on the second year, in which case they'd all be sorted based on the re-ordering of $data[1].

I can do this easily with array_multisort:

array_multisort($data[1],SORT_ASC,$data[0],$data[2]);

That's fine, but I don't know how many years of data there will be. I want some way of specifying just the right number of arguments, but I don't know how to do that in php, unless I just have to have an if statement for each possible number of years, which seems incredibly painful:

if ($num_years == 1)
{
    array_multisort($data[$which_year],SORT_ASC);
}
else if ($num_years == 2)
{
    array_multisort($data[$which_year],SORT_ASC,$data[0],$data[1]); // this does work, interestingly, in spite of the repetition...
}

Anyone know of a better way?

Thanks,

Ben

+2  A: 

You can always use call_user_func_array, specifying array_multisort as the first parameter and building an array of parameters to be passed to array_multisort. Something like:

$params = array();
foreach($data as $year){
  $params[] = $year;
}
call_user_func_array('array_multisort', $params);
Seb
Ah! Cool. That sounds like exactly what I need. I'll try it out.
Ben
It works! One thing: you need to add the arrays into the $params array by reference, otherwise it doesn't work. So: $params[] =
Ben