Sort multidimensional array by second-level key

橙三吉。 提交于 2020-01-02 07:10:13

问题


I have an array that looks like this:

array(3) { 
    ["Fall Quarter 2012"]=> array(2) { 
          [20121018]=> array(1) { 
              ["agenda"]=> string(55) "Fall_2012/Agenda_20121018.pdf" 
          }
          [20121011]=> array(2) { 
              ["agenda"]=> string(55) "Fall_2012/Agenda_20121011.pdf" 
              ["minutes"]=> string(56) "Fall_2012/Minutes_20121011.pdf" 
          } 
    } 
    ["Spring Quarter 2012"]=> array(1) { 
          [20120413]=> array(1) { 
              ["agenda"]=> string(57) "SPRing_2012/Agenda_20120413.pdf" 
          } 
    } 
    ["Summer Quarter 2012"]=> array(1) { 
          [20120610]=> array(2) { 
              ["agenda"]=> string(57) "Summer_2012/Agenda_20120610.pdf" 
              ["minutes"]=> string(58) "Summer_2012/Minutes_20120610.pdf" 
          } 
    } 
 }

And I'd like to sort it using date keys so that quarters are in the right order Fall/Summer/Spring. Which should look like this:

array(3) { 
    ["Fall Quarter 2012"]=> array(2) {
          [20121018]=> array(1) { 
              ["agenda"]=> string(55) "Fall_2012/Agenda_20121018.pdf" 
          }
          [20121011]=> array(2) { 
              ["agenda"]=> string(55) "Fall_2012/Agenda_20121011.pdf" 
              ["minutes"]=> string(56) "Fall_2012/Minutes_20121011.pdf" 
          } 
    }
    ["Summer Quarter 2012"]=> array(1) { 
          [20120610]=> array(2) { 
              ["agenda"]=> string(57) "Summer_2012/Agenda_20120610.pdf" 
              ["minutes"]=> string(58) "Summer_2012/Minutes_20120610.pdf" 
          } 
    } 
    ["Spring Quarter 2012"]=> array(1) { 
          [20120413]=> array(1) { 
              ["agenda"]=> string(57) "SPRing_2012/Agenda_20120413.pdf" 
          } 
    } 
 }

Is there a way to get this result by sorting using date, or should I use uksort() function to sort quarters with my own pattern?

Please, let me know what you think! Thank you!


回答1:


you should use the uasort function. Your code could look something like this:

function myComparison($a, $b){
    return (key($a) > key($b)) ? -1 : 1;
} 

uasort ( $quarters , 'myComparison' );

That will sort using $quarters["Fall Quarter 2012"]["20121018"] for example



来源:https://stackoverflow.com/questions/12865167/sort-multidimensional-array-by-second-level-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!