(first posted: Sep 17, 2006)
(1401 Reads)
keywords: articles php sort
Permalink
Sorting items on a field
This is useful, for example, when you do an Aritlces getall and need to sort on a dynamic data field.
Example usage:
<xar:set name="arts">xarModApiFunc( 'articles', 'user', 'getall', array('ptid'=>'12', 'extra'=>array('dynamicdata') ))</xar:set>
xar:set name="sorted">xarModApiFunc( 'articles', 'user', 'sortitems', array('items'=>$arts, 'field'=>'year_founded', 'order'=>'DESC'))</xar:set>
I've submitted this to the Xaraya development team, we'll see if it's accepted, rejected, or changed.
<?php
/**
* author: linoj
*
* array $args['items'] array of item arrays (like as returned by articles getall)
* string $args['field'] name of field to sort on
* string $args['order'] one of ASC, DESC, [default ASC]
* returns sorted array of items
Note: I do bubble sort by hand because the $field arg is not in scope of a compare function for usort()
TODO: allow 'field' to be a list of fields and/or an array of fields
*/
function articles_userapi_sortitems( $args )
{
extract($args);
// Argument check
if (!isset($items) || count($items)<1) {
$msg = xarML('Invalid #(1) for #(2) function #(3)() in module #(4)',
'items list', 'user', 'sortitems',
'Articles');
xarErrorSet(XAR_USER_EXCEPTION, 'BAD_PARAM',
new SystemException($msg));
return false;
}
if (!isset($field)) {
$msg = xarML('Invalid #(1) for #(2) function #(3)() in module #(4)',
'field', 'user', 'sortitems',
'Articles');
xarErrorSet(XAR_USER_EXCEPTION, 'BAD_PARAM',
new SystemException($msg));
return false;
}
$array_size = count($items);
if (!empty($order) && ($order == 'DESC'))
{
for($x = 0; $x < $array_size; $x++) {
for($y = 0; $y < $array_size; $y++) {
if($items[$x][$field] > $items[$y][$field]) {
$hold = $items[$x];
$items[$x] = $items[$y];
$items[$y] = $hold;
}
}
}
}
else
{ // assume ASC
for($x = 0; $x < $array_size; $x++) {
for($y = 0; $y < $array_size; $y++) {
if($items[$x][$field] < $items[$y][$field]) {
$hold = $items[$x];
$items[$x] = $items[$y];
$items[$y] = $hold;
}
}
}
}
return $items;
}
?>




Sorting items on a field
Posted by: Tim Stalker on December 21, 2006 10:44 AM#