How to get all parent ID of the categories?

Good afternoon.

The conclusion categories, for example the article: https://phpdes.com/php/postroenie-dereva-kategorij...

INSERT INTO `categories` (`id`, `parent_id`, `name`) VALUES
(1, 0, 'Section 1'),
(2, 0, 'Section 2'),
(3, 0, 'Section 3'),
(4, 1, 'Section 1.1'),
(5, 1, 'Section 1.2'),
(6, 4, 'Section 1.1.1'),
(7, 2, 'Section 2.1'),
(8, 2, 'Section 2.2'),
(9, 3, 'Section 3.1');


//Select data from database
$result=mysql_query("SELECT * FROM categories");
//If in the database there is a record generated by an array
if (mysql_num_rows($result) > 0){
 $cats = array();
//In a loop formed by an array of sections, the key will be the id of the parent category, as well as an array of sections, the key is the id of the category
 while($cat = mysql_fetch_assoc($result)){
 $cats_ID[$cat['id']][] = $cat;
 $cats[$cat['parent_id']][$cat['id']] = $cat;
}
}


function build_tree($cats,$parent_id,$only_parent = false){
 if(is_array($cats) and isset($cats[$parent_id])){
 $tree = '<ul>';
if($only_parent==false){
 foreach($cats[$parent_id] as $cat){
 $tree .= '<li>'.$cat['name'].' #'.$cat['id'];
 $tree .= build_tree($cats,$cat['id']);
 $tree .= '</li>';
}
}elseif(is_numeric($only_parent)){
 $cat = $cats[$parent_id][$only_parent];
 $tree .= '<li>'.$cat['name'].' #'.$cat['id'];
 $tree .= build_tree($cats,$cat['id']);
 $tree .= '</li>';
}
 $tree .= '</ul>';
}
 else return null;
 return $tree;
}


But my structure of website products belong to only a finite category, and how to get products from root category, I don't understand. That is, I can't write the logic:

If the final choice as to its ID (the current category) ?
Otherwise: how to get a list of the IDs of all parent categories ?


Thank you.
April 4th 20 at 00:28
3 answers
April 4th 20 at 00:30
Add another json field for "bread crumbs", where you specify (at creation of the category) all id and names from the root to the current, including the current one.

And the problem with recursive fetching from the database, including the load on the database - will be gone soon.
Yeah, and then one item it will be necessary to remove - Trystan_Crona commented on April 4th 20 at 00:33
@Trystan_Crona, the same as for create.
Since the modification of the tree - this is a rare procedure for the resource-intensive validation - pays Slavoj. - godfrey_Wilkinson commented on April 4th 20 at 00:36
I can not understand, you're just a fool with 0 experience in practical tasks, or a subtle Troll. - Trystan_Crona commented on April 4th 20 at 00:39
Tell me at least approximately where to start. - ruth48 commented on April 4th 20 at 00:42
@Trystan_Crona, I'm just not a fan. - godfrey_Wilkinson commented on April 4th 20 at 00:45
April 4th 20 at 00:32
this is garbage.

nested sets
April 4th 20 at 00:34
In a loop.

Find more questions by tags PHP