Blog スタッフブログ

PHP システム開発

[PHP]多次元配列を特定のキーの値でソート

システム開発担当のTFです。

やり方

  • array_column関数で、特定キーの要素を取り出す
  • array_multisort関数で、特定キーの要素を元に多次元配列をソートする

参考

  array_column
  array_multisort

サンプル


	$datas = [
		[
			'sort' => 2,
			'name' => "test2",
		],
		[
			'sort' => 3,
			'name' => "test3",
		],
		[
			'sort' => 1,
			'name' => "test1",
		],
	];

	// 多次元配列からsortの要素を取得する
	$sorts = array_column($datas, 'sort');

	/*
	var_dump($sorts);
	array(3) {
		[0]=>
			int(2)
		[1]=>
			int(3)
		[2]=>
			int(1)
	}
	*/
	
	// $datasをsortの順で並び変え
	array_multisort($sorts, SORT_ASC, $datas);
	
	/*
	var_dump($datas);
	array(3) {
		[0]=>
			array(2) {
				["sort"]=>
					int(1)
				["name"]=>
					string(5) "test1"
			}
		[1]=>
			array(2) {
				"sort"]=>
					int(2)
				["name"]=>
					string(5) "test2"
			}
		[2]=>
			array(2) {
				["sort"]=>
					int(3)
				["name"]=>
					string(5) "test3"
			}
	}
	*/
?>

Warning: Undefined array key 0 in /home/fl0uhem6u4/mixltd.jp/public_html/cms/wp-content/themes/mix_theme/pagination-single.php on line 3

Warning: Attempt to read property "cat_ID" on null in /home/fl0uhem6u4/mixltd.jp/public_html/cms/wp-content/themes/mix_theme/pagination-single.php on line 3

Warning: Attempt to read property "post_title" on string in /home/fl0uhem6u4/mixltd.jp/public_html/cms/wp-content/themes/mix_theme/pagination-single.php on line 9