LoginSignup
8
4

More than 5 years have passed since last update.

PHPのarray_columnで連想配列でネストされたキーを取得できるのか

Posted at

配列の特定のキーのものだけを取得する際に、(個人的に)array_columnを使う事が多い。
で、ネストされた連想配列ではどうなるの?って思ったので試してみる。

array_column

実験

公式のサンプルから拝借。

sample
<?php
$records = [
    [
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ],
    [
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    ],
    [
        'id' => 5342,
        'first_name' => 'Jane',
        'last_name' => 'Jones',
    ],
    [
        'id' => 5623,
        'first_name' => 'Peter',
        'last_name' => 'Doe',
    ]
];

$first_names = array_column($records, 'first_name');
print_r($first_names);

これの出力は以下のようになる。

output
Array
(
    [0] => John
    [1] => Sally
    [2] => Jane
    [3] => Peter
)

ここで、$recordsの配列をちょっと変えてみる。
first_nameとlast_nameをprofileというキーにいれる。

sample2
<?php
$records = [
    [
        'id' => 2135,
        'profile' => [
            'first_name' => 'John',
            'last_name' => 'Doe',
        ]
    ],
    [
        'id' => 3245,
        'profile' => [
           'first_name' => 'Sally',
           'last_name' => 'Smith',
        ]
    ],
    [
        'id' => 5342,
        'profile' => [
           'first_name' => 'Jane',
           'last_name' => 'Jones',
        ]
    ],
    [
        'id' => 5623,
        'profile' => [
           'first_name' => 'Peter',
           'last_name' => 'Doe',
        ]
    ]
];

$first_names = array_column($records, 'first_name');
print_r($first_names);

結果は・・・

output2
Array
(
)

むぅ。。取得出来ませんでした。。。

おまけ

ちなみに、

$first_names = array_column($records, 'first_name');

の部分を

$profiles = array_column($records, 'profile');
$first_names = array_column($profiles, 'first_name');

という具合に二回分ければ取得できるのだが、他に良いやり方ないかな。。。

まとめ

PHPのarray_columnで連想配列でネストされたキーを取得できませんでした。

8
4
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
8
4