问题
Let's say I've got an Article
s 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 id
s, 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