Wednesday, June 8, 2011

How do I sort a multidimensional array in php

How do I sort a multidimensional array in php

Method 1:
<?php
class TableSorter {
  protected $column;

  function __construct($column) {
    $this->column = $column;
  }

  function sort($table) {
    usort($table, array($this, 'compare'));

    return $table;
  }

  function compare($a, $b) {
    if ($a[$this->column] == $b[$this->column]) {
      return 0;
    }

    return ($a[$this->column] < $b[$this->column]) ? -1 : 1;
  }
}

$arr = array();

$arr[] = array('IBM', 'NYSE', 100);
$arr[] = array('MSFT', 'NASDAQ', 400);
$arr[] = array('GOOG', 'NASDAQ', 200);
$arr[] = array('AAPL', 'NASDAQ', 50);

$sorter = new TableSorter(2); // sort by third column
$arr = $sorter->sort($arr);

echo '<pre>';
print_r($arr);
echo '</pre>';
?>


Method 2:
<?php
$arr = $index = array();

$arr[] = array('IBM', 'NYSE', 100);
$arr[] = array('MSFT', 'NASDAQ', 400);
$arr[] = array('GOOG', 'NASDAQ', 200);
$arr[] = array('AAPL', 'NASDAQ', 50);

foreach ($arr as $key => $row) {
    $index[$key]  = $row[2];
    // of course, replace 2 with whatever is the field's index
}

array_multisort($index, SORT_ASC, $arr);

echo '<pre>';
print_r($arr);
echo '</pre>';
?>

Reference: http://stackoverflow.com/questions/96759/how-do-i-sort-a-multidimensional-array-in-php

No comments: