I need a result of an array that is flattenened like this:
$result = ["1", "2", "3", "4", "5", "6", "7"];
I have a DB result of this query:
$articles = DB::table('articles')
->where('is_published', 'true')
->get()
->pluck('category');
When I do this with this result:
$unflattened_array = $articles->toArray();
dd($unflattened_array);
The result looks like this:
And when I continue with trying to put the ones in arrays and spread then in just one big array as elements:
$flattened_array = array_merge(...$unflattened_array);
dd($unflattened_array);
I am getting this error message in Laravel:
array_merge(): Argument #1 must be of type array, string given
What am I doing wrong?
I want the array look like:
["2","3","4","5","6","8","22","45","46","70","100","102","105","106","107","205"]
2
Answers
Your each array element is JSON array, so you must first decode it:
Example
To provide a more laravel centric approach using collections:
This will return the flattened unique category IDs as a collection object, which you can transform to a normal array using
->toArray()