Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to flatten a collection with items of array in Laravel

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    $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:

enter image description here

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"]

>Solution :

Your each array element is JSON array, so you must first decode it:

foreach ($unflattened_array as $items) {
    array_push($flattened_array, ...json_decode($items));
}

$flattened_array = array_unique($flattened_array);

Example

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading