2

I'm working on a little project based on codeigniter, I'm not a php developer and this is my problem:

       foreach ($checkeds['id_iscritti'] as $checked){

        $iscritto = $this->pellegrinaggio_iscritti_m->get_iscritto($checked);

        $utente = $this->utenti_m->get_utente($iscritto[0]->id_utente);

        echo ("utente:   <pre> ");var_dump($utente);echo ("   </pre> \n\n");

    }

this is the code, it basically generate an associative array

and this is what i obtain from the var_dump:

array(1) { [0]=>
  object(stdClass)#38 (27) {
    ["id"]=>
    string(3) "254"
    ["nome"]=>
    string(13) "Padre EDUARDO"
    ["cognome"]=>
    string(9) "ANATRELLA"    
  }
}

utente:
 array(1) {
  [0]=>
  object(stdClass)#37 (27) {
    ["id"]=>
    string(3) "338"
    ["nome"]=>
    string(4) "ELSA"
    ["cognome"]=>
    string(5) "PAONE"      
  }
}

How can i sort the array $utenti by the index "nome"? I've spent some hours, to understand how this kind of array works, without any results, can you help me?

gagan mahatma
  • 336
  • 2
  • 9

2 Answers2

1

This is the function you want: http://php.net/manual/en/function.array-multisort.php

Your code should look something like this:

$sorted = array_multisort($utente, 'nome', SORT_ASC);
KWeiss
  • 2,954
  • 3
  • 21
  • 37
  • Correct me if I am wrong but i'm sure `array_multisort()` only sorts arrays of arrays, not arrays of objects? – RCrowt Jan 10 '16 at 08:14
  • 1
    It seems you're right, I missed that. The other answer (yours) is correct. – KWeiss Jan 10 '16 at 13:29
0

PHPs usort() function allows you to sort array using a custom function.

Assuming your array of objects is stored in $utente, the following will compare each object against each other object using the anonymous comparison function.

In the following code the $utente array will be sorted ascending by nome value.

usort($utente, function($a, $b){
   if ($a->nome > $b->nome) {
      return 1;
   }elseif($a->nome < $b->nome){
      return -1;
   }else{
     return 0;
   }
});

More details can be found at http://php.net/manual/en/function.usort.php

RCrowt
  • 921
  • 10
  • 19