TechniqueUse the usort() function on your result set: <?php // ldap sort function // sort by common name length (cn) function ldap_sort_func($a, $b) { if (!is_array($a) !is_array($b) $a[cn] == $b[cn]) return 0; return strlen($a[cn]) > strlen($b[cn]) ? 1 : -1; } // connect and bind $lh = ldap_connect("localhost") or die("Cannot Connect"); ldap_bind($lh) or die("Cannot Bind"); // Build the search and attributes we want $search_query = "sn=bro*"; $attributes = array("cn", "objectclass", "mail"); // Perform that thar query and load the results into an array $sth = ldap_search($lh, "o=Sterling's Company, c=US", $search_query, $attributes); $entries = ldap_get_entries($lh, $sth); ldap_free_result($sth); // Print out all the good information that we have collected echo "$entries[count] matching entries were found"; // now sort the results usort($entries, 'ldap_sort_func'); while ($idx < $entries[count]) { echo 'Well ' . $entries[$idx][cn] . ' seems to have matched;'; echo ' if you want to talk to him his e-mail is '; echo $entries[$idx][mail] .".\n<br>\n"; $idx++; } // close the connection ldap_close($lh); ?> CommentsTo sort a list of LDAP results, we first fetch all the results of our search into a two-dimensional array as described in recipe 17.5. Then we use the usort() function to custom sort the two-dimensional array returned by ldap_get_entries() . |