Laravel の pluck()
メソッドの仕様について学ぼうと思い公式ドキュメントを参照したのですが、サンプルコードの結果が理解できません。
公式ドキュメント
https://laravel.com/docs/5.4/collections#method-pluck
非公式日本語ドキュメント
https://readouble.com/laravel/5.4/ja/collections.html#method-pluck
pluck()
The pluck method retrieves all of the values for a given key:
php
1$collection = collect([ 2 ['product_id' => 'prod-100', 'name' => 'Desk'], 3 ['product_id' => 'prod-200', 'name' => 'Chair'], 4]); 5 6$plucked = $collection->pluck('name'); 7 8$plucked->all(); 9 10// ['Desk', 'Chair']
You may also specify how you wish the resulting collection to be keyed:
php
1$plucked = $collection->pluck('name', 'product_id'); 2 3$plucked->all(); 4 5// ['prod-100' => 'Desk', 'prod-200' => 'Chair']
疑問
「返り値のコレクションのキー項目も指定できます。」という説明文の意味自体は何となく理解できるのですが、二つ目のサンプルコードの結果の部分がなぜそうなるのか、そうなるとどういう状況で便利になるのかが理解できません。
1:
まず、(一つ目のサンプルコードと違い、)返り値はなぜ連想配列?になるのでしょうか。
2:
一つ目のサンプルコードのように
['Desk', 'Chair', 'prod-100', 'prod-200']
とならないのはなぜなのでしょうか。
3:
pluck()
呼び出し時に引数に先に 'name'
を渡しているにも関わらず、 'product_id'
の値である 'prod-100'
や 'prod-200'
がキーとなり、 その値が 'Desk'
や 'Chair'
となるのはなぜなのでしょうか。
ご教授のほどよろしくお願い申し上げます。

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/06/30 07:33