多次元配列のソート

array_multisortを使ったに多次元配列のソート方法

PHP

// 多次元配列 $words[0] = array( 'id' => '1', 'word' => 'Apple', 'meaning' => 'リンゴ' ); $words[1] = array( 'id' => '2', 'word' => 'Banana', 'meaning' => 'バナナ' ); $words[2] = array( 'id' => '3', 'word' => 'Cat', 'meaning' => 'ネコ' ); $words[3] = array( 'id' => '4', 'word' => 'Dog', 'meaning' => 'イヌ' ); $words[4] = array( 'id' => '5', 'word' => 'Coffee', 'meaning' => 'コーヒー' ); $words[5] = array( 'id' => '6', 'word' => 'Milk', 'meaning' => 'ミルク' ); $words[6] = array( 'id' => '7', 'word' => 'Tennis', 'meaning' => 'テニス' ); $words[7] = array( 'id' => '8', 'word' => 'Basketball', 'meaning' => 'バスケットボール' ); if (! empty($words)) { for ($i = 0; $i < count($words); $i++) { foreach($words[$i] as $wordKey => $wordVal) { $arr[$wordKey][] = $wordVal; } } } /* print_r($arr); Array ( [id] => Array ( [0] => 1 [1] => 2 (略) [6] => 7 [7] => 8 ) [word] => Array ( [0] => Apple [1] => Banana (略) [6] => Tennis [7] => Basketball ) [meaning] => Array ( [0] => リンゴ [1] => バナナ (略) [6] => テニス [7] => バスケットボール ) ) */ // word順は$arr['word']、meaning順は$arr['meaning'] // 昇順はSORT_ASC、降順はSORT_DESC array_multisort( $arr['word'], SORT_ASC, $words );

word順

Array ( [0] => Array ( [id] => 1 [word] => Apple [meaning] => リンゴ ) [1] => Array ( [id] => 2 [word] => Banana [meaning] => バナナ ) [2] => Array ( [id] => 8 [word] => Basketball [meaning] => バスケットボール ) [3] => Array ( [id] => 3 [word] => Cat [meaning] => ネコ ) [4] => Array ( [id] => 5 [word] => Coffee [meaning] => コーヒー ) [5] => Array ( [id] => 4 [word] => Dog [meaning] => イヌ ) [6] => Array ( [id] => 6 [word] => Milk [meaning] => ミルク ) [7] => Array ( [id] => 7 [word] => Tennis [meaning] => テニス ) )

meaning順

Array ( [0] => Array ( [id] => 4 [word] => Dog [meaning] => イヌ ) [1] => Array ( [id] => 5 [word] => Coffee [meaning] => コーヒー ) [2] => Array ( [id] => 7 [word] => Tennis [meaning] => テニス ) [3] => Array ( [id] => 3 [word] => Cat [meaning] => ネコ ) [4] => Array ( [id] => 8 [word] => Basketball [meaning] => バスケットボール ) [5] => Array ( [id] => 2 [word] => Banana [meaning] => バナナ ) [6] => Array ( [id] => 6 [word] => Milk [meaning] => ミルク ) [7] => Array ( [id] => 1 [word] => Apple [meaning] => リンゴ ) )

最新の記事

プロフィール

流されるままにウェブ業界で仕事しています。主にLAPP環境でPHPを書いています。最近はjQueryで遊んでいます。
※動作確認について