閲覧数:1177
投稿日:2020-06-05
更新日:2020-06-05
2次元配列を指定キーでソートするuser定義関数
1つのキーを基準にソートする
コード
$dataAryAll= [ 0 => [ 'id' => '2', 'topic_news_date' => '2014-07-09', ], 1 => [ 'id' => '5', 'topic_news_date' => '2017-12-02', ], 2 => [ 'id' => '5', 'topic_news_date' => '2019-12-26', ], 3 => [ 'id' => '5', 'topic_news_date' => '2017-12-26', ], ]; var_export($dataAryAll); //指定キーに対応する値を基準に、2次元配列をソートする function sortAryAllByKeyU($keyName, $sortOrder, $ary) { foreach ($ary as $key => $val) { $keyAry[$key] = $val[$keyName]; } array_multisort($keyAry, $sortOrder, $ary); return $ary; } //'topic_news_date'を降順ソートする $resultAryAll = sortAryAllByKeyU('topic_news_date', SORT_DESC, $dataAryAll); var_export($resultAryAll);
結果
//ソート前2次元配列 array ( 0 => array ( 'id' => '2', 'topic_news_date' => '2014-07-09', ), 1 => array ( 'id' => '5', 'topic_news_date' => '2017-12-02', ), 2 => array ( 'id' => '5', 'topic_news_date' => '2019-12-26', ), 3 => array ( 'id' => '5', 'topic_news_date' => '2017-12-26', ), ) //ソート後2次元配列 array ( 0 => array ( 'id' => '5', 'topic_news_date' => '2019-12-26', ), 1 => array ( 'id' => '5', 'topic_news_date' => '2017-12-26', ), 2 => array ( 'id' => '5', 'topic_news_date' => '2017-12-02', ), 3 => array ( 'id' => '2', 'topic_news_date' => '2014-07-09', ), )