60
47

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で連想配列の配列から特定キーの配列を取り出す - array_column

Posted at

「まさかそんな便利なメソッドないだろ〜」と思って調べたらあったのでメモ。

以下のような連想配列の配列なデータがあって、
そのうちのキーidのみの配列が欲しいときの話です。

$users = array(
    array(
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ),
    array(
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    ),
    array(
        'id' => 5342,
        'first_name' => 'Jane',
        'last_name' => 'Jones',
    )
);

普通にやると、ループを回して新しい配列に詰め直す必要がありそうですが、

$id_list = array_column( $users, 'id' );

↑たったこれだけで実現できます。
### 結果

print_r( $id_list );
Array
(
    [0] => 2135
    [1] => 3245
    [2] => 5342
)

参考

PHP: array_column - Manual

60
47
1

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
60
47

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?