简体   繁体   English

PHP使用Usort对多维数组进行排序

[英]PHP Using Usort to sort a multidimensional array

I've seen similar questions, I simply do not understand the answers. 我见过类似的问题,我根本不理解答案。 Hopefully if I ask specifically about my code something will click. 希望我是否专门询问我的代码,然后单击。 I've been stuck for some time and would really appreciate the help. 我已经停留了一段时间,非常感谢您的帮助。

I have an array: foreach ($showresult as $display) { $display_result[] = array ('parkid' =>$display['parkid'], 我有一个数组:foreach($ showresult as $ display){$ display_result [] = array('parkid'=> $ display ['parkid'],

                 'trailsys' =>$display['trailsys'],

                         'trailset' =>$display['trailset'],

                         'name' =>$display['name'], 

                         'description' =>$display['description'], 

                         'url' =>$display['url'], 

                                 'ldes' =>$display['ldes'],

                                 'ltxt' =>$display['ltxt'],

                         'address' =>$display['address'], 

                         'city' =>$display['city'], 

                         'zip' =>$display['zip'], 

                         'phone' =>$display['phone'], 

                         'pos' =>$display['pos'],   

                         'T1' => $display['systemname'],

                 'T2'=> $display['name']);

 {                           'state' =>$display['state'], 

Every item in the array has a value in T1. 数组中的每个项目在T1中都有一个值。 T2 can have a value, or it can be 0. I want to alphabetize the list by T1. T2可以有一个值,也可以是0。我想按T1的字母顺序排列列表。 In some cases, there will be three or four entries where T1 is the same, then I want to alphabetize those by T2. 在某些情况下,将有三到四个条目,其中T1相同,然后我想按T2字母顺序排列。 I'm stumped. 我很沮丧

Please help. 请帮忙。

You should try with usort() function ( http://www.php.net/usort ). 您应该尝试使用usort()函数( http://www.php.net/usort )。 It allows you to sort array by custom function. 它允许您通过自定义函数对数组进行排序。 So, in your case it would be something like: 因此,在您的情况下,它将类似于:

<?
  usort($array,function($a,$b) {
    if ($a['T1'] < $b['T1']) return -1;
    elseif ($a['T1'] > $b['T1']) return 1;
    else {
      if ($a['T2'] < $b['T2']) return -1;
      elseif ($a['T2'] > $b['T2']) return 1;
      else return 0;
    }
  });
?>

You could check it out and adjust to your needs. 您可以检查出来并适应您的需求。

Let me know if this works for you. 让我知道这是否适合您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM