Search code examples
phparrayssorting

Sort a 2d array by column value


How can I sort this array by the last_modified value?

array(1606) {
  [0]=>
  array(16) {
    ["name"]=>
    string(16) "La casa de papel"
    ["last_modified"]=>
    string(10) "1586198606"
  }
  [1]=>
  array(16) {
    ["name"]=>
    string(8) "Sintonia"
    ["last_modified"]=>
    string(10) "1586015522"
  }
  [2]=>
  array(16) {
    ["name"]=>
    string(10) "Outra Vida"
    ["last_modified"]=>
    string(10) "1608409121"
  }
  [3]=>
  array(16) {
    ["name"]=>
    string(15) "Law & Order: UK"
    ["last_modified"]=>
    string(10) "1619515436"
  }
}

at the moment, this is my code, nothing special:

$position = 0;
while ($position < count($arr)) {
    
    echo $arr[$position]["name"] . " - ";
    echo date('d/m/Y - H:i', $arr[$position]["last_modified"]) . "<br>\n";
    $position = $position + 1;

}

Solution

  • usort() should do it:

    usort($arr, function($a, $b){return $a['last_modified']<=>$b['last_modified'];});
    

    To reverse the order of the sort, reverse the order of the parameters passed to the callback function.

    Demo: https://3v4l.org/NPOu9

    Reference: usort()