1
2

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 5 years have passed since last update.

PHPの多次元連想配列でキー名を保持しつつ子連想配列の特定キーでソート

Last updated at Posted at 2018-01-10

1年に1回くらい必要になり、そのたびに妙に時間かけてググっている気がするので…

以下のようなデータ構造で定義されたT○KI○のメンバーを身長(降順)でソートする場合を想定します。
array_multisortだとメンバー名のところが吹っ飛ぶのでuasortを使います。

usort.php
<?php

$ary = [
  "shigeru" => ["height" => 173, "birthday" => '1970/11/17', "出身地" => "奈良県"],
  "tatsuya" => ["height" => 167, "birthday" => '1972/01/10', "出身地" => "埼玉県"],
  "taichi" => ["height" => 167, "birthday" => '1974/09/02', "出身地" => "東京都"],
  "masahiro" => ["height" => 181, "birthday" => '1977/01/11', "出身地" => "北海道"],
  "tomoya" => ["height" => 184, "birthday" => '1978/11/07', "出身地" => "神奈川県"],
];

uasort($ary, function($x, $y) {
    $key = 'height';
    if ( $x[$key] == $y[$key] ) { return 0; }
    else if ( $x[$key] > $y[$key] ) { return -1; }
    else { return 1; }
});

var_dump($ary);

結果です。


array(5) {
  ["tomoya"]=>
  array(3) {
    ["height"]=>
    int(184)
    ["birthday"]=>
    string(10) "1978/11/07"
    ["出身地"]=>
    string(12) "神奈川県"
  }
  ["masahiro"]=>
  array(3) {
    ["height"]=>
    int(181)
    ["birthday"]=>
    string(10) "1977/01/11"
    ["出身地"]=>
    string(9) "北海道"
  }
  ["shigeru"]=>
  array(3) {
    ["height"]=>
    int(173)
    ["birthday"]=>
    string(10) "1970/11/17"
    ["出身地"]=>
    string(9) "奈良県"
  }
  ["tatsuya"]=>
  array(3) {
    ["height"]=>
    int(167)
    ["birthday"]=>
    string(10) "1972/01/10"
    ["出身地"]=>
    string(9) "埼玉県"
  }
  ["taichi"]=>
  array(3) {
    ["height"]=>
    int(167)
    ["birthday"]=>
    string(10) "1974/09/02"
    ["出身地"]=>
    string(9) "東京都"
  }
}
1
2
0

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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?