LoginSignup
1
0

More than 3 years have passed since last update.

多次元配列を時間順に並び替える

Posted at

概要

データベースの結果を多次元の配列に代入して時間順に並び替えたのでその方法をメモします。

結論

array_multisort( array_map( "strtotime", array_column( $data, "created_at" ) ), SORT_DESC, $array ) ;

一つずつ見ていきます。

実装

こんな感じの配列

$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 ) ;

結果

$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",
            }

];

無事時間順に並び替えることができました。

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0