Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

513
Visualizações
Why using unset() function cast the array to object?

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?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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);
over 4 years ago · Santiago Trujillo Relatório

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda