Using Laravel's pluck method without an associative array

泄露秘密 提交于 2019-12-25 08:16:12

问题


Let's say I've got an Articles collection, and I want to fetch the popular articles.

So first, I make a scopePopular() method in the Article method. Very simple.

Now I want to fetch their ids, so I'll do this:

Article::popular->pluck('id');

The result will be an associative array:

[
    0 => 1,
    1 => 34,
    2 => 17
    ...
];

I want to get a normal array, without the keys, Like:

[1, 34, 17]

I know I can just do something like this:

array_values(Article::popular->pluck('id'));

But I believe Laravel has much more cleaner way to do this. Any ideas?


回答1:


All arrays have indexes.

[
    0 => 1,
    1 => 34,
    2 => 17
];

equals to

[1, 34, 17]

In other words:

$a1 = [0 => 1, 1 => 34, 2 => 17];
$a2 = [1, 34, 17];
$a1 === $a2;
// returns True



回答2:


You can use values() method which is wrapper for array_values():

Article::popular->pluck('id')->values();



回答3:


Its exactly what you need and what you get, By default php has the incremental key from 0.

You want to see something like a JSON array I assume. Just do a return the array and you will see the JSOn array in browser, but internally its like this only.

Please confirm and let me know.Thanks



来源:https://stackoverflow.com/questions/41568941/using-laravels-pluck-method-without-an-associative-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!