0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【PHP】多次元配列内の配列を、配列の要素を元に並び替える方法

Last updated at Posted at 2023-05-10

使用する機会があったのでメモです。

// 配列を日付で昇順に並べたい
$data = [
    ['2023-04-11', '20', 'hoge'],
    ['2023-04-24', '30', 'hoge'],
    ['2023-04-03', '40', 'fuga']
];
// 各配列の0番目の要素で並び替え
array_multisort(array_map("strtotime", array_column($data, '0')), SORT_ASC, $data);

var_dump($data);
出力結果
array(3) {
  [0]=>
  array(3) {
    [0]=>
    string(10) "2023-04-03"
    [1]=>
    string(2) "40"
    [2]=>
    string(4) "hoge"
  }
  [1]=>
  array(3) {
    [0]=>
    string(10) "2023-04-11"
    [1]=>
    string(2) "20"
    [2]=>
    string(4) "hoge"
  }
  [2]=>
  array(3) {
    [0]=>
    string(10) "2023-04-24"
    [1]=>
    string(2) "30"
    [2]=>
    string(4) "hoge"
  }
}

追記:
@ss8826さんがコメントにて、より簡潔な書き方を教えてくださいました✨
ありがとうございました!

参考

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?