How to sort an array in PHP

Asked

Viewed 60 times

-1

I have the following code that picks up data from the server via ldap, where the $info returns me an array ,I’m trying to sort alphabetically using the function sort but unsuccessfully ,when I print my table it remains out of order.

inserir a descrição da imagem aqui ...

$result_search = ldap_search($ds, $ldap_base_dn, $search_filter, $attributes);
 if ($result_search) {
   $info = ldap_get_entries($ds, $result_search);
     $retorno = ldap_count_entries($ds, $result_search);
     $tabela = '<div id ="scrollbar">';
     $tabela .= '<table id="myTable">';
     $tabela .= '<thead>';
     $tabela .= '<tr>';
     $tabela .= '<th>Nome</th>'; 
     $tabela .= '<th>Telefone</th>';
     $tabela .= '</tr>';
     $tabela .= '</thead>';
     $tabela .= '<tbody>';
     foreach ($info as $key) {
         sort($info);
       if ( isset($key ['displayname'] [0] ) &&isset($key['telephonenumber'] [0]  )){
         $tabela .= '<tr>'; 
         $tabela .= '<td>'.$key ['displayname'] [0].'</td>'; 
         $tabela .= '<td>'.$key ['telephonenumber'] [0].'</td>';
         $tabela .= '</tr>';}

This is my return from the variable $info inserir a descrição da imagem aqui

  • the sort is before the foreach ! but also the code is with usort

  • It was fitting now with the example of array.

  • 1

    Thanks for your attention and help @NOVIC

1 answer

3


The Sort in this case is not recommended, use the usort which has a function to specify which element you want to sort in the case is the name and with the function strcmp that compares the string, example:

usort($info, function($a, $b) {
    return strcmp($a['displayname'][0], $b['displayname'][0]); 
});

An Online Example

Note: This event is before displaying the information on the screen, in your case before the foreach, example:

// primeiro ordena
usort($info, function($a, $b) {
    return strcmp($a['displayname'][0], $b['displayname'][0]); 
});
// depois mostra o resultado
foreach ($info as $key) {
  • Thanks for the reply, but I had tried this and it brings me the error message Warning: strcmp() expects Parameter 2 to be string, array Given in C: xampp htdocs agenda index.php on line 69 which is exactly the point of ordering.

  • I saw your question change, which is the big bad that do not put all the explanation and made the adequacy @KALIBBAN

  • 1

    Yes ,it worked!! Thank you so much for the help and sorry I didn’t put the return right at the start.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.