LoginSignup
7
6

More than 5 years have passed since last update.

PHPでpluck

Last updated at Posted at 2018-04-11

PHPでのpluck関数はarray_columnです。

フレームワーク等にpluckがあったりするので無いものと思いがちだったり、個人的に忘れやすいのでメモ。

ドキュメントを確認するとオブジェクトにも対応していて(PHP7)、結果配列のキーも設定できる。

$records = 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',
    ),
    array(
        'id' => 5623,
        'first_name' => 'Peter',
        'last_name' => 'Doe',
    )
);

$first_names = array_column($records, 'first_name');
print_r($first_names);
Array
(
    [0] => John
    [1] => Sally
    [2] => Jane
    [3] => Peter
)
7
6
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
7
6