1

I have a database list which looks this:

ID      Name      Parent_ID
1       Cat 1     NULL
2       Cat 2     NULL
3       Cat 3     2
4       Cat 4     3
5       Cat 5     1
6       Cat 6     2

The out put that I am trying to get is all the categories arranged in order of hierarchy and sorted alphabetically. Like this:

Cat 1
    Cat 5
Cat 2
    Cat 3
        Cat 4
    Cat 6

I am really not sure how to quite get this result, this is what I have at the moment, but does not work:

 SELECT * from Categories AS parent 
 LEFT JOIN Categories AS child ON child.Parent_ID = parent.ID

Any help is appreciated.

Alex
  • 21,273
  • 10
  • 61
  • 73
Paul
  • 2,465
  • 8
  • 35
  • 60
  • possible duplicate of [Hierarchical recursion menu with PHP/MySQL](http://stackoverflow.com/questions/607052/hierarchical-recursion-menu-with-php-mysql) – BlitZ Jan 18 '14 at 10:36
  • @HAL9000 No. There are only 2 levels – voodoo417 Jan 18 '14 at 10:39
  • If you know that there are only a couple of levels to your tree, just outer join the table to itself as often as could be required. – Strawberry Jan 18 '14 at 12:12
  • Thank you for the responses. In this instance there are only a couple of levels, however it could go much deeper. – Paul Jan 18 '14 at 12:58

1 Answers1

0

I think, you need build categories tree in PHP. Try it (example):

$sql = 'SELECT * from Categories ORDER BY parent_id ASC'; 
$items = // fetch as array of assoc.arrays

// example
// $items = array(
//     array('id' => 3, 'parent_id' => 1 ,'name'=>'..'),
//     array('id' => 4, 'parent_id' => 3, ,'name'=>'..'),
//     array('id' => 7,  'parent_id' => 0, ,'name'=>'..'),
//);

$childs = array();
foreach($items as &$item) $childs[$item['parent_id']][] = &$item;
unset($item);

foreach($items as &$item) if (isset($childs[$item['id']]))
    $item['childs'] = $childs[$item['id']];
unset($item);

$tree = $childs[0];

echo '<pre>';
print_r($tree);
echo '</pre>';
voodoo417
  • 11,861
  • 3
  • 36
  • 40
  • 1
    I think it is better to use recursion in such a case. Get root categories, than recursively get parent cat and parent of those parent until you get "nothing", than process to another root directory – ASTRALiENS Jan 18 '14 at 11:01
  • @ASTRALiENS its one of solution :) – voodoo417 Jan 18 '14 at 11:05
  • Thank you for these solutions. I suppose that the question is which would produce the fastest results. I would assume that a single MYSQL query and processed PHP would be the fastest, as opposed to multiple SQL queries. I will try this out, but thank you very much! – Paul Jan 18 '14 at 13:01