Michael J.A. Clark
Michael Clark is a professional software developer who creates high-quality products for startups in Cambridge, UK. Skills: C#, Java, PHP, XHTML, AS3, CSS, ML.

Sections

Contact details

Email
mjac@mjac.co.uk
Skype
mjacdotuk
Twitter
mjacuk

Recursive category sorting for a MySQL creation system

My new project library uses a MySQL database instead of serializing PHP data directly to disk. phpMyAdmin can be used for adding content, instead of having to maintain a custom solution. The most complicated feature to implement was subcategories and sorting them required a recursive algorithm:

function catSort($rawList, $parentId = 1)
{
	$base = array();
	$toSort = array();

	foreach ($rawList as $id => $item) {
		if ($item['parent'] === $parentId && $id !== 1) {
			$base[$id] = $item;
		} else {
			$toSort[$id] = $item;
		}
	}

	foreach ($base as $id => $item) {
		$base[$id]['children'] = $this->catSort($toSort, $id);

		foreach ($base[$id]['children'] as $child) {
			$base[$id]['total'] += $child['total'];
		}
	}

	return $base;
}

Comments