note 66731 deleted from ref.array by felipe

[email protected]
Newsgroups php.notes
Message-ID <[email protected]>
Note Submitter: php_spam at erif dot org 

----

Public domain, yadda yadda.  This is an extension of the assocSort below, patched up a bit.  Feedback would be wonderful.

<?php

  function assocMultiSort(&$array,$keys,$directions=true) {
    if (!is_array($array) || count($array) == 0) return true;
    if (!is_array($keys)) { $keys = Array($keys); }

    //we want "current" instead of necessarily the "zeroth" element; there may not be a zeroth element
    $test = current($array);

    $assocSortCompare = '';

    for ($i=0,$count=count($keys);$i<$count;$i++) {
      $key = $keys[$i];
      if (is_array($directions)) {
        $direction = $directions[$i];
      } else {
        $direction = $directions;
      }
      if ($i > 0) $assocSortCompare .= 'if ($retval != 0) return $retval; ';
      $assocSortCompare .= '$ax = $a["'.$key.'"]; $bx = $b["'.$key.'"];';

      //TODO -- if it's "blank", search up the list until we find something not blank
      if (is_numeric($test[$key]) || ($test[$key] == ((int)$test[$key]))) {
        if ($direction) {
          $assocSortCompare.= ' $retval = ($ax == $bx) ? 0 : (($ax < $bx) ? -1 : 1);';
        } else {
          $assocSortCompare.= ' $retval = ($ax == $bx) ? 0 : (($ax < $bx) ? 1 : -1);';
        }
      } else {
        if ($direction) {
          $assocSortCompare.= ' $retval = strcmp($ax,$bx);';
        } else {
          $assocSortCompare.= ' $retval = strcmp($bx,$ax);';
        }
      }
    }

    $assocSortCompare.= ' return $retval;';
    $assocSortCompare = create_function('$a,$b',$assocSortCompare);
    $retval = usort($array,$assocSortCompare);
    return $retval;
  }

?>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.