PHP Doku:: Sortiert LDAP Ergebniseinträge - function.ldap-sort.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzSonstige DiensteLightweight Directory Access ProtocolLDAP Funktionenldap_sort

Ein Service von Reinhard Neidl - Webprogrammierung.

LDAP Funktionen

<<ldap_set_rebind_proc

ldap_start_tls>>

ldap_sort

(PHP 4 >= 4.2.0, PHP 5)

ldap_sort Sortiert LDAP Ergebniseinträge

Beschreibung

bool ldap_sort ( resource $link , resource $result , string $sortfilter )

Warnung

Diese Funktion ist bis jetzt nicht dokumentiert. Es steht nur die Liste der Argumente zur Verfügung.


8 BenutzerBeiträge:
- Beiträge aktualisieren...
thorben at kapp-hamburg dot de
7.01.2011 13:46
I wondered how to sort after a dn, for just show a tree view. I tried to set $sortfilter = 'dn', but that didn't work. Than I tried with a blank string ''. That worked, the entries are sorted by dn.
renandelima at gmail dot com
26.08.2008 6:40
I was very unhappy because doesn't exists a way to order ldap search results. Above a solution to order a search in ascending and descending order. This function also do pagination.

// descending order
$list = ldap_sort_paginate( $conn, $search, "cn", "desc" );

// ascending order with pagination
$list = ldap_sort_paginate( $conn, $search, "cn", "asc", 3, 15 );

Use http://php.net/ldap_count_entries to calculate the min and max pages values before call this function. The first page value is 0 (zero).

<?php

/**
 * Order a search in ascending and descending order.
 *
 * @param resource from ldap_connect()
 * @param resource from ldap_search()
 * @param string of attribute to order
 * @param string "asc" or "desc"
 * @param integer page number, first is 0 zero
 * @param integer entries per page
 * @return string[]
 */
function ldap_sort_paginate( $rConnection, $rSearch, $sField, $sOrder = "asc", $iPage = null, $iPerPage = null )
{
   
$iTotalEntries = ldap_count_entries( $rConnection, $rSearch );
    if (
$iPage === null || $iPerPage === null )
    {
       
# fetch all in one page
       
$iStart = 0;
       
$iEnd = $iTotalEntries - 1;
    }
    else
    {
       
# calculate range of page
       
$iStart = ( ceil( $iTotalEntries / $iPerPage ) - 1 ) * $iPage;
       
$iEnd = $iStart + $iPerPage - 1;
        if (
$sOrder === "desc" )
        {
           
# revert range
           
$iStart = $iTotalEntries - 1 - $iEnd;
           
$iEnd = $iStart + $iPerPage - 1;
        }
    }
   
var_dump( $iStart . " " . $iEnd );
   
# fetch entries
   
ldap_sort( $rConnection, $rSearch, $sField );
   
$aList = array();
    for (
       
$iCurrent = 0, $rEntry = ldap_first_entry( $rConnection, $rSearch );
       
$iCurrent <= $iEnd && is_resource( $rEntry );
       
$iCurrent++, $rEntry = ldap_next_entry( $rConnection, $rEntry )
    )
    {
        if (
$iCurrent >= $iStart )
        {
           
array_push( $aList, ldap_get_attributes( $rConnection, $rEntry ) );
        }
    }
   
# if order is desc revert page's entries
   
return $sOrder === "desc" ? array_reverse( $aList ) : $aList;
}
ccblanket at yahoo dot com
5.03.2005 18:30
It is interesting people are using all these methods to sort multi-attribute results from LDAP searches. Well, here is a simpler one. Just use ldap_sort once for each sort attribute in the reverse order of importance.

--hikmet

<?php
    $ldapFilterAttributes
= array ('givenname', 'sn', 'mail');
   
$ldapSortAttributes = array('sn', 'givenname'); // ie. sort by givenname, then by sn
   
   
$ldapFilter = "(&(sn='')(givenname=''))";
   
   
$ldapBaseDN = 'ou=users, dc=example, dc=com';
   
   
$search = @ldap_search($ldapConnect, $ldapBaseDN, $ldapFilter, $ldapFilterAttributes) ;
    if (!(
$search)) {
        die(
"Unable to search LDAP server");
    }

   
// lets sort the results by firstname if firstname is in the results
   
foreach ($ldapSortAttributes as $eachSortAttribute) {
        if (
in_array($eachSortAttribute, $ldapFilterAttributes)) { // making sure we don't accidentally try to sort against an inexisting field
           
ldap_sort($this->connect, $search, $eachSortAttribute);
        }
    }

   
// and here is the result
   
$results = ldap_get_entries($this->connect, $search);
?>


[EDIT BY danbrown AT php DOT net: Bugfix by (huntz AT huntz DOT org) on 17-MAY-2005: Nice tip, but on line 2 of your example we need to use $ldapSortAttributes and not $ldapSortAttribues :-)]
ben at xsusio dot com
3.09.2004 23:33
If you are wanting to sort by multiple attributes, for instance ordering by last name and then first name,  try this function. This is similar to "ORDER BY lastname, firstname"  in SQL.

This function uses an insertion sort algorithm, which is somewhat faster then the old-fashoned bubble sort.  The second argument is an array containing the attributes you want to sort by. (this functon won't do descending or ascending..  feel free to add it!)

<?php
/**
 * @param array $entries
 * @param array $attribs
 * @desc Sort LDAP result entries by multiple attributes.
*/
function ldap_multi_sort(&$entries, $attribs){
    for (
$i=1; $i<$entries['count']; $i++){
       
$index = $entries[$i];
       
$j=$i;
        do {
           
//create comparison variables from attributes:
           
$a = $b = null;
            foreach(
$attribs as $attrib){
               
$a .= $entries[$j-1][$attrib][0];
               
$b .= $index[$attrib][0];
            }
           
// do the comparison
           
if ($a > $b){
               
$is_greater = true;
               
$entries[$j] = $entries[$j-1];
               
$j = $j-1;
            }else{
               
$is_greater = false;
            }
        } while (
$j>0 && $is_greater);
       
       
$entries[$j] = $index;
    }
    return
$entries;
}
?>
zbaizman at yahoo dot com
7.08.2004 3:15
This note may be self-evident, but the functionality of ldap_sort threw off this sometime user of relational databases.

The following code will NOT do what you expect:

<?php

// omitted calls to connect and and bind to LDAP server...

// attributes we want to retrieve from LDAP server
$ldap_attributes = array ( 'cn', 'o', 'mail' ) ;

// retrieve attributes from matching entries
$search_results = ldap_search ( $ldap_conn, 'dc=example,dc=org', '(objectclass=*)', 0, 500, 30 ) ;

// sort entries by last name ('sn')
ldap_sort ( $ldap_conn, $search_results, 'sn' ) ;

?>

The entries will NOT be sorted by last name. Why not? Because LDAP doesn't function like a RDBMS; you cannot sort a result set on an arbitrary field, regardless of whether you "selected" it. You must always include the attribute by which you want to sort your entries among the requested attributes (add 'sn' to $ldap_attributes, in this case).

Hope this is helpful to some other folks who scratched their heads when they tried to sort entries and it didn't work out...
askgopal at sify dot com
4.09.2003 17:07
Here's a simple LDAP sort function I wrote:

<?php
function sort_ldap_entries($e, $fld, $order)
{
    for (
$i = 0; $i < $e['count']; $i++) {
        for (
$j = $i; $j < $e['count']; $j++) {
           
$d = strcasecmp($e[$i][$fld][0], $e[$j][$fld][0]);
            switch (
$order) {
            case
'A':
                if (
$d > 0)
                   
swap($e, $i, $j);
                break;
            case
'D':
                if (
$d < 0)
                   
swap($e, $i, $j);
                break;
            }
        }
    }
    return (
$e);
}

function
swap(&$ary, $i, $j)
{
   
$temp = $ary[$i];
   
$ary[$i] = $ary[$j];
   
$ary[$j] = $temp;
}
?>

so that it can be invoked like:

<?php
    $entries
= sort_ldap_entries($entries, 'mail', 'A'); // sort entries by ascending order of mail
?>

where,
    `$entries' is the array returned by ldap_get_entries() function.

This might be useful to those who still run older versions of PHP (<= 4.2.0) on their web servers :-)
jason dot sokolowski at rotork dot com
6.09.2002 22:51
Something real simple i wrote to sort directory searches by a persons last name.

<?php
for($i=0;$i<$result["count"];$i++)
{

$lastname = $result[$i]["sn"][0];

$lnames["$i"]=$lastname;

}
//for i

@asort($lnames);
?>
matthew dot j dot gray at uwrf dot edu
25.06.2002 23:47
This function applies strcmp() to each attribute (given by sortfilter) in order to sort the entries returned by the server.  To order search results ascending by last name, try passing "sn" as the sortfilter argument.  This function does not play nice with multi-valued attributes.



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)