I have a problem with sorting of an array.
$infoGroup is the result of a ‘ldap_get_entries’ call earlier. As I step through this array I put the result in the array $names.
Then I want to sort $names in alfabetical order, I have tried a number of different methods but to no avail. The array always stays in the same order it was constructed.
What have I missed?
foreach($infoGroup[$i]['member'] as $member) {
//echo "<li>".$member;
$go = stripos($member, "n");
unset($names);
$ai++;
if ( $go == 1 ) {
// extract member name from string
$temp = substr($member, 0, stripos($member, ","));
// Strip the CN= and change to lowercase for easy handling
$temp = str_replace("cn=", "", $temp);
$names[$ai] = ($temp);
}
if (natsort($names)){
foreach ($names as $key => $val) {
echo "<li>";
echo "$key $val";
}
}
}
$ai = 0;
This is the result however I try to sort the $names array:
- Henrik Lindbom
- Klaus Rödel
- Admin
- Bernd Brandstetter
- proxyuser
- Patrik Löfström
- Andreas Galic
- Martin Stalder
Hmmm.. a bit hard to explain, but the issue is because you are sorting your array inside that
foreach()loop. Essentially, since you are creating the array element in the iteration of the first loop, thenatsort()only has 1 element to sort and your nestedforeach()loop is only outputting that 1 element, which is then unset() at the second and further iterations…Extract that second
foreach()that sorts and outputs and remove theunset()from the top of the first loop. This should output your desired results.Something like this…