1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

plunk()とarray_column()

Posted at

plunk()

コレクションから特定のキーの値を抽出する

$users = collect([
    ['id' => 1, 'name' => 'John'],
    ['id' => 2, 'name' => 'Jane'],
    ['id' => 3, 'name' => 'Doe'],
]);

$names = $users->pluck('name');
// $namesは ['John', 'Jane', 'Doe'] となる

array_column()

多次元配列から特定のカラムを抽出する

$users = [
    ['id' => 1, 'name' => 'John'],
    ['id' => 2, 'name' => 'Jane'],
    ['id' => 3, 'name' => 'Doe'],
];

$names = array_column($users, 'name');
// $namesは ['John', 'Jane', 'Doe'] となる

まとめ

どちらも特定のカラムを抽出するために便利
pluck()はLaravelコレクションに対して使われ、
array_column()はPHPの配列に対して使われる

個人的に使っていて感じたのは深い階層でも使える分plunk()は優秀だなと感じた。
PHPの連想配列ではarray_column()は使えなかった。
別の関数を使って実装する必要がある。

$users = collect([
    ['id' => 1, 'profile' => ['name' => 'John']],
    ['id' => 2, 'profile' => ['name' => 'Jane']],
    ['id' => 3, 'profile' => ['name' => 'Doe']],
]);

$names = $users->pluck('profile.name');
// $names は ['John', 'Jane', 'Doe'] となる
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?