mgd_sort_id_array()

This is the core of the sorting magic. It sorts any id-array with a specified key field.

Calling Syntax

mgd_sort_id_array (&$array, $sortkey, $object_type, $sorting)

Parameter Syntax

$array is the array to be sorted. It is passed by reference and is therefore sorted in place. It is an Array of Object IDs (read: primary keys).

$sortkey is a field of the Objects to be sorted (see below). It has to be accessible with the syntax $object->$sortkey. If you prepend this field with "reverse", the sorting order is reversed. (i.e. "abstract" and "reverse abstract" for sorting MidgardArticles.)

$object_type holds the name of the classes that have to be sorted. These classes must have an ID-Element (as do all Midgard Objects) which is used to instantinate a specific Object. References to Midgard Classes go with their real class name (i.e. "MidgardArticle" or "MidgardTopic"). Midgard Objects use "mgd_get_xxx($id)" for construction, all other objects use "new xxx($id)". See the function mgd_get_createstr() for further information.

$sorting is the SortOrder according to PHPs sort-function.

Dependencies

Code

<?php

function mgd_sort_id_array (&$array, $sortkey, $object_type,
  
$sorting = SORT_REGULAR) {
  
  
$createstr = mgd_get_createstr($object_type);
  
  if (
count($array) == 0)
    return array();
  
  
$sortkey = trim ($sortkey);
  
$sortkey_word = explode(" ", $sortkey);
  
  switch (
count ($sortkey_word)) {
    case
1:
      
$reverse = false;
      break;
    
    case
2:
      if (
$sortkey_word[0] != "reverse")
        die (
"mgd_sort_id_array. First Parameter of \$sortkey "
          
. "($sortkey_word[0]) invalid. aborting");
      
$sortkey = $sortkey_word[1];
      
$reverse = true;
      
      break;
    
    default:
      die (
"mgd_sort_id_array: Parameter count in \$sortkeyey "
        
. "($sortkey) wrong, aborting.");
      break;
  }
  
  
$sortarray = array();
  
$result = array();
  
  foreach (
$array as $elementid)
  {
    eval(
"\$tmp = $createstr($elementid);");
    
$sortarray[$tmp->id] = $tmp->$sortkey;
  }
  
  
asort ($sortarray, $sorting);
  
reset($sortarray);
  
  while(list(
$key, $value) = each ($sortarray))
    
$result[] = $key;
  
  
$array = ($reverse) ? array_reverse($result) : $result;
}

?>