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?

0

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Correct me if I am wrong but i'm sure array_multisort() only sorts arrays of arrays, not arrays of objects?
It seems you're right, I missed that. The other answer (yours) is correct.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.