I create navigation for the site and for life I can not understand recursion. I have all my data stored through MySQL using this design:

I read some links about how recursion works, and I have to be slow because I find it hard to understand. I tried to write something, and I know that it is not even close to what I really need, but this is the beginning:
PDO
public function viewCategories() { $viewSQL = "SELECT * FROM categories"; try { $pdo = new PDO('mysql:host=localhost;dbname=store','root',''); $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); $categoryVIEW = $pdo->prepare($viewSQL); $categoryVIEW->execute(); $array = $categoryVIEW->fetchAll(PDO::FETCH_ASSOC); $categoryVIEW->closeCursor(); $json = json_encode($array); return $json; } catch(PDOexception $e) { return $e->getMessage(); exit(); } }
recursion
$return = json_decode($category->viewCategories(),true); function buildNavigation($json) { foreach($json as $item) { if($item['category_id'] === $item['parent']) { print('<li>'.$item['category_name'].'</li>'); if($item['category_id'] === $item['parent']) { print('<li>match'.$item['category_name'].'</li>'); buildNavigation($json); } } } buildNavigation($return);
as expected, this will never enter into a condition. I tried to figure it out on my own because it is a good thing to know, but I guess that goes beyond my mental capacity :(
Thanks for watching :)
UPDATE
I know that an answer has already been given, but is there a way to do this to create an associative array? I played with a function that ALMOST works for me, which I got from HERE , but adds an extra array that I DO NOT want.
Method
private function buildCategories($array,$parent) { $result = array(); foreach($array as $row) { if($row['parent'] == $parent) { $result[$row['category_name']] = $this->buildCategories($array,$row['category_id']); } } return $result; } $json = json_encode($this->buildCategories($array,NULL)); return $json;
I want it:
{"reloading":{"components","presses and dies","tumblers & scales","tools & accessories","shotshell reloading"}
but I get the following:
{"reloading":{"components":[],"presses and dies":[],"tumblers & scales":[],"tools & accessories":[],"shotshell reloading":[]}