概要
データベースの結果を多次元の配列に代入して時間順に並び替えたのでその方法をメモします。
結論
array_multisort( array_map( "strtotime", array_column( $data, "created_at" ) ), SORT_DESC, $array ) ;
一つずつ見ていきます。
実装
こんな感じの配列
.php
$data=[
{
"post_id": 76,
"user_id": 3,
"description": "hogehoge",
"created_at": "2021-02-08T09:59:52.000000Z",
},
{
"post_id": 77,
"user_id": 2,
"description": "hogehoge",
"created_at": "2021-02-11T12:08:44.000000Z",
}
{
"post_id": 78,
"user_id": 2,
"description": "hogehoge",
"created_at": "2021-01-26T21:50:47.000000Z",
}
];
時間順に並べたいのでcreated_at
から参照して並び替えます。
array_multisort( ソートしたい配列 , ソート順 ,ソート方法(省略可) , 追加の配列 )
今回ソートしたい配列は$dataですがcreated_at
が英文日付なので、UNIXタイムスタンプ形式にする必要があります。
ですのでarray_map()関数を使います。
array_map(コールバック関数, $配列)
ですので、
array_map("strtotime",array_column( $data, "created_at" ) )
で日付を比較できるように変換します。
array_multisort( array_map( "strtotime", array_column( $data, "created_at" ) ), SORT_DESC, $array ) ;
結果
.php
$data=[
{
"post_id": 78,
"user_id": 2,
"description": "hogehoge",
"created_at": "2021-01-26T21:50:47.000000Z",
},
{
"post_id": 76,
"user_id": 3,
"description": "hogehoge",
"created_at": "2021-02-08T09:59:52.000000Z",
},
{
"post_id": 77,
"user_id": 2,
"description": "hogehoge",
"created_at": "2021-02-11T12:08:44.000000Z",
}
];
無事時間順に並び替えることができました。