Page 1 of 1

Need help on sorting an array for output in smarty template [SOLVED]

Posted: Tue Mar 16, 2010 7:37 pm
by Splynx
Hello people,

how do I go about sorting an array I have made for input in the smarty template so I do not have to make the sort in SQL.

Here is the code that makes declarations to place via smarty in the template

Code: Select all

$records = array();
while ($catresult !== false && $catrow = $catresult->FetchRow()) {
	$project_id = $catrow['project_id'];
	$pro_query = 'SELECT * FROM '.cms_db_prefix().'module_csrproject WHERE project_id = ?';
	$pro_result = $db->Execute($pro_query,array($project_id));
	while ($pro_result !== false && $pro_row = $pro_result->FetchRow()) {
		$region_id = $pro_row['region_id'];
		$project_order = $pro_row['order_id'];
		$project_name = $pro_row['project_name'];
		$project_facts = $pro_row['project_facts'];
		$project_details = $pro_row['project_details'];							
	}
	$record = new stdClass();
	$record->id = $project_id;
	$record->order = $project_order;
	$record->region = $region_id;
	$record->name = $project_name;
	$record->facts = $project_facts;
	$record->details = $project_details;
	$records[] = $record;

}
I want the array sorted by the $project_order, and I am not able to sort the list with the SQL ORDER BY order_id no I am not, so don't go there  ;)

I want the array I deliver to smarty to be sorted via a PHP or smarty sort function for arrays.

Can anyone help?

Re: Need help on sorting an array for output in smarty template [SOLVED]

Posted: Tue Mar 16, 2010 7:45 pm
by Splynx
Here is the solution

Code: Select all

function sortStdArray($array,$index)
{
$sort=array() ;
$return=array() ;

for ($i=0; isset($array[$i]); $i++)
$sort[$i]= $array[$i]->{$index};

natcasesort($sort) ;

foreach($sort as $k=>$v)
$return[]=$array[$k] ;

return $return;
}
Then just call

Code: Select all

$records = sortStdArray($records,"order");