Sort Multi Array in PHP

后端 未结 9 1905
清酒与你
清酒与你 2021-01-23 07:10

Does anybody have an idea how can I sort this array by key (date) in PHP?

Array
(   
    [2011-02-16] => Array
        (
            [date] => 2011-02-16
          


        
相关标签:
9条回答
  • 2021-01-23 07:57

    Sure thing. I answered this exact post yesterday, too.

    Sorting 2 arrays to get the highest in one and lowest in another

    In your case, it will be something like...

    $myArray= subval_sort($myArray,'date'); 
    
    function subval_sort($a,$subkey) {
        foreach($a as $k=>$v) {
            $b[$k] = strtolower($v[$subkey]);
        }
        asort($b);
        foreach($b as $key=>$val){
            $c[] = $a[$key];
        }
        return $c;
    }
    

    EDIT

    The answer by shamittomar is better though :)

    0 讨论(0)
  • 2021-01-23 08:02

    Use the uasort function, which is user customizable sorting. Like this:

    function cmp($a, $b)
    {
        if ($a['date'] == $b['date'])
        {
            return 0;
        }
        return ($a['date'] < $b['date']) ? -1 : 1;
    }
    
    uasort($your_array, "cmp");
    
    0 讨论(0)
  • 2021-01-23 08:02

    Well, as sorting on the key would do it, ksort() would work for you!

    But if you really want to sort on the date element, you would use uasort() with a sort function like this

      function compare($a, $b)
      {
          if ($a['date']==$b['date']) return 0;
          return ($a['date']>$b['date'])?1:-1;
      }
    
      uasort($myarray, 'compare');
    
    0 讨论(0)
  • 2021-01-23 08:03

    have you tried ksort? http://www.php.net/manual/en/function.ksort.php

    0 讨论(0)
  • 2021-01-23 08:04

    This should help you brush up on the basics of array sorting in PHP

    http://www.the-art-of-web.com/php/sortarray/

    Something like this would sort your problem however:

    usort($array, "cmp");
    
    function cmp($a, $b){ 
        return strcmp($b['date'], $a['date']); 
    
    0 讨论(0)
  • 2021-01-23 08:04

    What you want is UASORT.

    http://us3.php.net/manual/en/function.uasort.php

    function would be like:

    function cmp($a, $b) {
        $d1 = strtotime($a['date']);
        $d2 = strtotime($b['date']);
        if ($d1 == $d2) {
           return 0;
        }
        return ($d1 < $d2) ? -1 : 1;
    }
    
    0 讨论(0)
提交回复
热议问题