勉強したことのメモ

Webエンジニア / プログラマが勉強したことのメモ

PHPで多次元連想配列のキーを指定してソートする方法

   2026/10/02  PHP

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

https://www.php.net/manual/ja/function.array-multisort.php

 - PHP

  関連記事

PHPでフォーム送信の際に禁止ワードのチェック及び制限をかける方法
PHPでフォーム送信の際に禁止ワードのチェック及び制限をかける方法

掲示板等のformを送信する際に特定の禁止ワードが含まれていないかチェックするプ ...

PHPで他サーバにFTP経由にてファイルをアップロードする方法
PHPで他サーバにFTP経由にてファイルをアップロードする方法

formで送信した内容をチェックした上で、他サーバにファイルをアップロードしたか ...

PHPで「operator not supported for strings」エラーの対応方法
PHPで「operator not supported for strings」エラーの対応方法

PHPにて「Fatal error: [] operator not suppo ...

PHPにて「みんなの自動翻訳」のAPIで指定したテキストの言語判定する方法
PHPにて「みんなの自動翻訳」のAPIで指定したテキストの言語判定する方法

迷惑メール対策等でメール本文が日本語のもののみ受信したい場合がある。ただ、本文内 ...

PHPにて短縮URLを展開させて、元のURLを取得する方法
PHPにて短縮URLを展開させて、元のURLを取得する方法

短縮されたURLを展開させて、元のURLを取得したいというケースがあった。方法を ...