【PHP】SQLの結果をソートする
問題
SQLで取得した結果を、phpでソートしたいです
答え
array_multisort が使えます。
SQLでソートするとすごく遅いなどの場合に
結果を全取得しても問題ないくらいであれば、
PHPでソートすることで速度の問題を解決できることも多いです。
以下のようなテーブルがあるとき、
| id | column1 | column2 | column3 |
|---|---|---|---|
| 1 | 1 | 1 | 1 |
| 2 | 1 | 1 | 2 |
| 3 | 1 | 2 | 1 |
| 4 | 1 | 2 | 2 |
| 5 | 2 | 1 | 1 |
| 6 | 2 | 1 | 2 |
| 7 | 2 | 2 | 1 |
| 8 | 2 | 2 | 2 |
カラム2の降順、IDの降順にソートする場合は
$pdoStatement = $this->pdo->query("SELECT * FROM test_sort");
// 全件取得
$dataCollection = $pdoStatement->fetchAll();
// 結果のキーとソートするカラムの値の配列を作って
$sortKey1Column2 = [];
$sortKey2Id = [];
foreach ($dataCollection as $key => $row)
{
$sortKey1Column2[ $key ] = $row->column2;
$sortKey2Id[ $key ] = $row->id;
}
// $dataCollection をソートする
// 自動判別(数値)で良いときは SORT_STRING は指定不要
array_multisort(
$sortKey1Column2 , SORT_DESC , SORT_STRING,
$sortKey2Id , SORT_DESC , SORT_STRING,
$dataCollection
);
結果は以下
array ( 0 => (object) array( 'id' => '8', 'column1' => '2', 'column2' => '2', 'column3' => '2', ), 1 => (object) array( 'id' => '7', 'column1' => '2', 'column2' => '2', 'column3' => '1', ), 2 => (object) array( 'id' => '4', 'column1' => '1', 'column2' => '2', 'column3' => '2', ), 3 => (object) array( 'id' => '3', 'column1' => '1', 'column2' => '2', 'column3' => '1', ), 4 => (object) array( 'id' => '6', 'column1' => '2', 'column2' => '1', 'column3' => '2', ), 5 => (object) array( 'id' => '5', 'column1' => '2', 'column2' => '1', 'column3' => '1', ), 6 => (object) array( 'id' => '2', 'column1' => '1', 'column2' => '1', 'column3' => '2', ), 7 => (object) array( 'id' => '1', 'column1' => '1', 'column2' => '1', 'column3' => '1', ), )