Populate a flat array with a dynamic number of values from each row of a result set

70 Views Asked by At

I have 2 tables one is category that has subcategories and I want to fetch the records and put in a single array. I have implemented this code:

public function searchItem(){
    $categories = ServiceCategory::with('subCategories')->get();

    $categoryArray = [];

    foreach ($categories as $category) {
        $categoryArray[] = [
            $category->category, 
            $category->subCategories->pluck('subcategory')->toArray(),
        ];
    }
    return $categoryArray;
}

The results I get is:

[["plumbing",["fitting","joints","pipe setting","wall setters","roof setters","drainage","walls and interior"]]

but what I want is something like this:

["plumbing","fitting","joints","pipe setting","wall setters","roof setters","drainage","walls and interior"]
2

There are 2 best solutions below

1
mickmackusa On BEST ANSWER

Your sample output seems to indicate that you are only getting one row of results from $categories, so I am not sure that you actually need that foreach() loop.

The only time I ever use array_push() is when it is necessary to push multiple items into an array. I find it very appropriate for this case to produce a flat result array.

public function searchItem(){
    $categoryArray = [];
    foreach (ServiceCategory::with('subCategories')->get() as $category) {
        array_push(
            $categoryArray,
            $category->category, 
            ...$category->subCategories->pluck('subcategory')->toArray()
        );
    }
    return $categoryArray;
}

Using this technique, the returned array will be a flat array thanks to the spread operator (...) before the plucked subCategories array.

1
Snehal S On

You can use array_merge(https://www.php.net/manual/en/function.array-merge.php) function of PHP. This will help you to merge elements of 2 arrays.

public function searchItem(){
    $categories = ServiceCategory::with('subCategories')->get();

    $categoryArray = [];

    foreach ($categories as $category) {
        $categoryArray = array_merge($categoryArray, 
            array_merge(
                [$category->category],
                $category->subCategories->pluck('subcategory')->toArray()
            )
        );
    }
    return $categoryArray;
}

We need to add $category->category as an array as from your given output it seems that its a string.