We're currently building a website with a categorized MySQL table containing various competences, and we noticed that the nested set model would be optimized for this. Although, we've got a pretty serious problem - the nested set model doesn't allow any sorting, and we really need that possibility. I'd like the output data to be array(id, name, depth), as this function supports (though without any kind of sorting):
function tree()
{
$query = 'SELECT node.id, node.name, (COUNT(parent.name) - 1) AS depth FROM test_competence AS node, test_competence AS parent WHERE node.lft BETWEEN parent.lft AND parent.rgt GROUP BY node.name ORDER BY node.lft';
$result = mysql_query($query) or die(mysql_error());
while($data = mysql_fetch_assoc($result))
{
$returnarray[] = $data;
}
return $returnarray;
}
I've started with a function but have no idea how to continue:
function tree_sorted()
{
//Get data
$query = 'SELECT node.id, node.name, node.parent, (COUNT(parent.name) - 1) AS depth FROM test_competence AS node, test_competence AS parent WHERE node.lft BETWEEN parent.lft AND parent.rgt GROUP BY node.name ORDER BY node.lft';
$result = mysql_query($query) or die(mysql_error());
//Fetch gotten data
while($data = mysql_fetch_assoc($result))
{
$fetched[$data['depth']][$data['id']] = array($data['name'], $data['parent']);
}
//Sort fetched data
foreach($fetched as $i => $row)
{
asort($row);
$sorted[$i] = $row;
}
//Merge sorted data (???)
foreach($sorted as $i => $arr)
{
foreach($arr as $x => $row)
{
$returnarray[] = array('id' => key($row), 'name' => $row[0], 'depth' => $x);
}
}
Any help would be greatly appreciated. I've googled for different ways to sort data from nested sets, but without any good result.
Thank you in advance.
EDIT: Now I've tried some with the uasort() function which feels to be the right way, but the problem still remain.