0
1

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

PHP連想配列のキーとバリューを組み替える方法

Posted at

DBから取ってきたデータをビューに渡す時に、中の要素でキーとバリューの組み合わせを作って新しい連想配列を作りたい場面があったのですが、色々調べてもどれもしっくりこなかったので、本記事を書いてみました。

例えば、下記のような都道府県と市区町村がセットになっているデータがあったとして、

$area_list = [
        ['prefecture' => '東京都', 'city' => '新宿'],
        ['prefecture' => '東京都', 'city' => '渋谷'],
        ['prefecture' => '東京都', 'city' => '原宿'],
        ['prefecture' => '大阪府', 'city' => '難波'],
        ['prefecture' => '大阪府', 'city' => '梅田'],
        ['prefecture' => '大阪府', 'city' => '京橋'],
        ['prefecture' => '愛知県', 'city' => '名古屋'],
        ['prefecture' => '愛知県', 'city' => '金山'],
        ['prefecture' => '愛知県', 'city' => '春日部']
    ];

これを下記のような、都道府県がキーで、市区町村がバリューの連想配列にしたいとします。

Array
(
    [東京都] => Array
        (
            [0] => 新宿
            [1] => 渋谷
            [2] => 原宿
        )

    [大阪府] => Array
        (
            [0] => 難波
            [1] => 梅田
            [2] => 京橋
        )

    [愛知県] => Array
        (
            [0] => 名古屋
            [1] => 金山
            [2] => 春日部
        )

)

色々PHPの配列操作について調べたり、if文書いたりしてみたんですが、試しに下記のコードを実行したところ、一発でうまくいきました。

$new_array = [];

foreach ($area_list as $area) {
    $new_array[$area['prefecture']][] = $area['city'];
}

$area_listのデータの順番が都道府県順に並んでいなくても、都道府県ごとのデータになります。

蓋を開けてみれば、とても簡単な話でした。
この半年ぐらいずっとプロジェクトでコード書いていて、だいぶ慣れてきたと思ったんですが、その分何か特別な関数が必要かと疑心暗鬼になってしまい、迷子になりかけてしまいました。

初心を忘れないようにします。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?