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"]
3
Answers
If you are using PHP >= 8.1 then use Array unpacking.
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.
We need to add
$category->category
as an array as from your given output it seems that its a string.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 thatforeach()
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.Using this technique, the returned array will be a flat array thanks to the spread operator (
...
) before the pluckedsubCategories
array.