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

125
Visualizações
Sort Array from object

I have an object and store it in an array. However, when outputting the names from the object, I want to sort them by 'is_main'. Thereby 'is_main' with the value 1 should always be in the first place and then 'is_main' with the value 0. Here is the Object

array(2){
   [
      1
   ]=> object(stdClass)#3729 (22){
    [
        "id_teacher"
     ]=> string(1)"2"[
        "firstname"
     ]=> string(6)"John"[
        "lastname"
     ]=> string(8)"Doe"[
        "is_main"
     ]=> string(1)"0"
   }[
      2
   ]=> object(stdClass)#3723 (22){
      [
         "id_teacher"
      ]=> string(1)"2"[
         "firstname"
      ]=> string(6)"John"[
         "lastname"
      ]=> string(8)"Brown"[
         "is_main"
      ]=> string(1)"1"
   }
}

And my PHP Code:

$storage = array();
foreach($data->class_teacher_arr[$item->id_class] as $reference) {
    $storage[] = $reference->firstname . ' ' . $reference->lastname . ' ' . $reference->is_main;
}
echo implode('<br/>', $storage);

I hope that someone can help me by this problem.

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

0

You can use usort with a callback defining what you're looking for in the sort function.

$teachers = $data->class_teacher_arr[$item->id_class];
usort($teachers, function ($teacher) {
    return isset($teacher->is_main) && !$teacher->is_main;
});

$storage = array();
foreach($teachers as $reference) {
    $storage[] = $reference->firstname . ' ' . $reference->lastname . ' ' . $reference->is_main;
}
echo implode('<br/>', $storage);

If the value is_main is set and is true(equals 1), it will go to the top of the array and once you echo out your storage variable, you will see all of the is_main teachers at the top.

Check out this documentation for callback sorting of arrays.

https://www.php.net/manual/en/function.usort.php

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