PHPで多次元連想配列のキーを指定してソートする方法
2026/10/02
PHPで多次元配列から指定したキーでソート(並べ替え)したい。以下に対応方法をメモ。
対応方法
ソースコード
$data = [ [ 'id' => 4, 'name' => '田中', ], [ 'id' => 1, 'name' => '鈴木', ], [ 'id' => 2, 'name' => '山田', ], [ 'id' => 3, 'name' => '佐々木', ], ]; var_dump($data); $idList = array_column($data, 'id'); array_multisort($idList, SORT_ASC, $data); var_dump($data);
出力結果
# ソート前
array(4) {
[0]=>
array(2) {
["id"]=>
int(4)
["name"]=>
string(6) "田中"
}
[1]=>
array(2) {
["id"]=>
int(1)
["name"]=>
string(6) "鈴木"
}
[2]=>
array(2) {
["id"]=>
int(2)
["name"]=>
string(6) "山田"
}
[3]=>
array(2) {
["id"]=>
int(3)
["name"]=>
string(9) "佐々木"
}
}
# ソート後
array(4) {
[0]=>
array(2) {
["id"]=>
int(1)
["name"]=>
string(6) "鈴木"
}
[1]=>
array(2) {
["id"]=>
int(2)
["name"]=>
string(6) "山田"
}
[2]=>
array(2) {
["id"]=>
int(3)
["name"]=>
string(9) "佐々木"
}
[3]=>
array(2) {
["id"]=>
int(4)
["name"]=>
string(6) "田中"
}
}
リファレンス
array_column
https://www.php.net/manual/ja/function.array-column.php
array_multisort
関連記事
-
-
PHPにて配列の出力時にジェネレータを利用してメモリを節約する方法
PHPにて大量のデータが格納された配列をforeach等でループ処理するような場 ...
-
-
CodeIgniter4で簡易版ログインシステムの実装方法(管理画面向け)
CodeIgniter4で管理画面向けの簡易版ログインシステムを作成したい。通常 ...
-
-
PHPから他サーバのAPIに対してPOST送信する方法
PHPから他サーバのAPIに対してPOSTでリクエストしたかった。GETだったら ...
-
-
Facebookのタイムラインを取得して表示する方法
Facebookのタイムラインを取得してきて、表示させたいという案件があった。 ...
-
-
PHPでtwitterとfacebookのいいねやフォローのカウント数を取得する方法
PHPでtwitterとfacebookのいいねやフォロー数を取得して表示させた ...