2009-05-25 18:42
浏览 39


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:


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)
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?

图片转代码服务由CSDN问答提供 功能建议

我有一个多维数组,基本上每年由一个子数组组成。 所以,例如,如果我有三年的数据,它可能看起来像这样:

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

现在我希望能够根据其中一年对这些数组进行排序。 例如,我可能想要根据第二年进行排序,在这种情况下,它们都会根据$ data [1]的重新排序进行排序。

我可以这样做 使用array_multisort轻松:

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

没关系,但我不知道会有多少年的数据。 我想要一些方法来指定恰当数量的参数,但我不知道如何在php中这样做,除非我只需要为每个可能的年数都有一个if语句,这看起来非常痛苦:

  if($ num_years == 1)
 array_multisort($ data [$ which_year],SORT_ASC); 
else if($ num_years == 2)\  n {
 array_multisort($ data [$ which_year],SORT_ASC,$ data [0],$ data [1]);  //有趣的是,这确实有效,尽管重复... 

任何人都知道更好的方法吗? < / DIV>

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongshi6710 2009-05-25 18:52

    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);
    解决 无用
    打赏 举报

相关推荐 更多相似问题