skip to Main Content

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:

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

2

Answers


  1. 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

    Login or Signup to reply.
  2. To provide a more laravel centric approach using collections:

    $articles = DB::table('articles')
        ->where('is_published', 'true')
        ->get()
        ->pluck('category');
    
    // Get the unique categegory IDs from articles.
    $categoryIds = $articles
        ->map(fn ($json) => json_decode($json))
        ->flatten()
        ->unique();
    

    This will return the flattened unique category IDs as a collection object, which you can transform to a normal array using ->toArray()

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search