Why using unset() function cast the array to object?

Viewed 234

Here is my code:

return ApiResponse::Json(200, '', ['categories' => $categories], 200);

And here is a screenshot of the result:

output 1

Now, I need to unset items inside categories collection based on a specific logic. So I wrote this loop:

foreach ($categories as $key => $category) {
    if ($category->BusinessSubCategory->isEmpty())
          unset($categories[0]);
}

return ApiResponse::Json(200, '', ['categories' => $categories], 200);

And here is my new result: (which is casted to an object)

output 2

Well .. What's wrong? How can I keep the old structure after unseting some items?

3 Answers

Try this:

foreach ($categories as $key => $category) {
    if ($category->BusinessSubCategory->isEmpty())
          unset($categories[$key]);

}

$categories = array_slice($categories->toArray(), 0, count($categories));

return ApiResponse::Json(200, '', ['categories' => $categories], 200);

The unset() method doesn't change your type.

Your 'array' is not an array but a collection.

Try:

foreach ($categories as $key => $category) {
    if ($category->BusinessSubCategory->isEmpty()) {
        unset($categories[0]);
        break;
    }
}
$categories = array_values($categories->toArray());

return ApiResponse::Json(200, '', ['categories' => $categories], 200);

Notice if you're unseting the same element you should break loop after do that.

Look like you are using relationship so you can do without loop

$category=Category::with('BusinessSubCategory')
                     ->has('BusinessSubCategory')
                     ->get();

or using collection

$result= $categories->filter(function ($category){
    
           return  $category->BusinessSubCategory->isNotEmpty();
        });

dd($result->values()->toArray());

if $categories is not collection then use collect($categories)->filter...

Related