Location: PHPKode > scripts > Dynamic Multisort > dynamic-multisort/sort.php
<?

/* class myDynMsort
    by Marco Tonnicchi - Germany Feb.2009
    hide@address.com

    This simple class can be used for sorting multidimensional Arrays
    with the standard function array_multisort().
    It provides a dynamic number of columns and criteria to be sorted.
    see following example.
    because Working with call_user_func_array( ) in my case in php5 doesnt works right( no sorting )
    this class create a dynamic array_multisort() function generating a  string
    that represantate the function array_multisort( )with all needed params.
    saving this into a temporarly with uniqid( ) generated php file and including them.
    after work is done the php file will be deleted immediately.

  Having fun and good results using this class

*/




/* begin Example */
$data[] = array( 'gender'=>'m','surname'=>'Doe', 'name'=>'john','salary'=>57000      );
$data[] = array( 'gender'=>'f','surname'=>'Hill','name'=>'Mary','salary'=>63000      );
$data[] = array( 'gender'=>'f','surname'=>'East','name'=>'Violet','salary'=>71000    );
$data[] = array( 'gender'=>'m','surname'=>'Reick','name'=>'Marcus','salary'=>78000   );
$data[] = array( 'gender'=>'m','surname'=>'Doe','name'=>'john','salary'=>58000       );
$data[] = array( 'gender'=>'f','surname'=>'Albert','name'=>'Cindy','salary'=>53000   );
$data[] = array( 'gender'=>'f','surname'=>'Albert','name'=>'Jane',' salary'=>53000   );

print " Unsorted Data <br> ";
print_r( $data );
print "<br> ";
print str_repeat('_',50);
$caseInsensitive = TRUE;
$ms = new myDynMsort( $data, $caseInsensitive );

/* after making intance of class
   add sorting criteria with public addSortCriteria method
   all sorting criteria would be placed in order of adding
   for example :
*/
$ms->addSortCriteria( 'gender', SORT_ASC,   SORT_STRING  );
$ms->addSortCriteria( 'surname',SORT_ASC,   SORT_STRING  );
$ms->addSortCriteria( 'salary', SORT_DESC,  SORT_NUMERIC );

/* will genetate following sorting:

first : column 'gender' ascending
second: column 'surname' ascending
third : column 'salary'descending


note: sortdir and sorttype are optional parameters
standard is sort_ASC , SORT_REGULAR
you can set any number of columns for sorting



after setting criteria -
method sort() returns sorted multidimensional array
*/
print " sorted DATA <br> ";
print_r( $ms->sort( ) );

/* END Example */

//######################################################################


class myDynMsort{

private $caseInsensitive;
private $matrix;
private $criteria;
private $columns;

//#######################################################################
/* public functions */
// contructor initialize parameters
public function __construct( $matrix, $caseInsensitive = TRUE  )  {
  $this->matrix = $matrix;
  $this->caseInsensitive  = $caseInsensitive;
  $this->columns = array();
  $this->criteria= array();
}


// sort multidimension array ()
 public function sort( ) {
   if (!$this->makeColumns())        return FALSE;
   if( !$this->makeFunctionFile() )  return FALSE;
   return $this->matrix;
 }


// adding a sorting criteria in array criteria
 public function addSortCriteria( $column , $sortdir = SORT_ASC , $sorttype = SORT_REGULAR  ) {
   $this->criteria[] = array( 'col'=>$column,'sdir' => $sortdir,'stype'=> $sorttype );
}

//#########################################################################
/* private functions */

// generate columns to sort
private function makeColumns( ){
  if( !count( $this->criteria ) )return FALSE;
  foreach( $this->matrix as $key => $row ){
  for( $i=0;$i<count( $this->criteria );$i++ ){
      $value = ( $this->caseInsensitive ) ? strtolower( $row[ $this->criteria[$i]['col'] ] ):$row[ $this->criteria[$i]['col'] ];
      $this->columns[$i][ $key ] = $value;
  }
 }
 return TRUE;
}

 //  create string of function and params for php file
 private function makestring( ){
 if (!count( $this->columns ) ) return FALSE;
    for( $i = 0;$i<count( $this->columns ); $i++){
      $str[] = '$this->columns['.$i.'],$this->criteria['.$i.'][\'stype\'],$this->criteria['.$i.'][\'sdir\']';
    }
    $fnc = "<?php \n\n array_multisort( ";
    $fnc.= implode( ',',$str );
    $fnc.= ',$this->matrix ); ';
    $fnc.=" \n\n ?>";
    return $fnc;
 
 
 }
 // generates a temporary php file within array_multisort function included all params

 private function makeFunctionFile( ) {
    $filename = uniqid('mtomto_').'.php';
    if( !$str = $this->makestring(  ) )         return FALSE;
    if( !$this->writefile( $str ,  $filename ) )return FALSE;
    if( !is_file( $filename ) )                 return FALSE;
    include_once( $filename );
    unlink( $filename );
    return TRUE;

 }
// save file
private function writefile( $string , $filename ) {
   $fp = fopen($filename,'w');
   if( !$fp ) return FALSE;
   fputs( $fp, $string  );
   fclose($fp);
   return TRUE;
}

}

/* if someone finds the reason because call_user_func_array doesnt work
please tell me ! thx */


/* doesnt works properly
 private function userFunc( ) {
    $array = array( );
    for ($i = 0;$i<count( $this->columns ); $i++ ) {

      $array[] = $this->columns[$i];
      $array[] = $this->criteria[$i]['stype'];
      $array[] = $this->criteria[$i]['sdir'];

    }
    $array[] = $this->matrix;

   $this->matrix = call_user_func_array('array_multisort', $array );
   return $this->matrix;

  }
*/
?>
Return current item: Dynamic Multisort