I'm having some trouble with recursive functions in PHP. I'm creating a function that creates a link based in categories in database. The table is created as infinite level with "parent_id" to check what's the parent ID of that category.
I've also included a field "category_link" that creates the link. My problem resides into creating the link system with recursive function.
For example I have the category: Cars (ID 1) (link /cars) -- Volvo (ID 2) (link /volvo) -- Audi (ID 3) (link /audi)
So, if I build a function to create the link for ID2, the final link is supposed to be /cars/volvo. My function is only retrieving the last one, /volvo instead /cars/volvo
function GetSlug($mysqli)
{
if (isset($_POST)) {
$cat = validar($mysqli, $_POST['card_category']);
if ($stmt = $mysqli->prepare("SELECT * FROM categories WHERE id = ? LIMIT 1")) {
$stmt->bind_param("i", $cat);
$stmt->execute() or trigger_error($stmt->error, E_USER_ERROR);
($stmt_result = $stmt->get_result()) or trigger_error($stmt->error, E_USER_ERROR);
if ($stmt_result->num_rows > 0) {
$category = array(
'categories' => array(),
'parent_cats' => array()
);
while ($row_data = $stmt_result->fetch_assoc()) {
$parent = $row_data['parent_id'];
//creates entry into categories array with current category id ie. $categories['categories'][1]
$category['categories'][$row_data['id']] = $row_data;
//creates entry into parent_cats array. parent_cats array contains a list of all categories with children
$category['parent_cats'][$row_data['parent_id']][] = $row_data['id'];
}
echo buildcat($parent, $category);
} else {
return false;
}
}
}
}
And the second function:
function buildcat($parent, $category)
{
$html = "";
if (isset($category['parent_cats'][$parent])) {
foreach ($category['parent_cats'][$parent] as $cat_id) {
if (!isset($category['parent_cats'][$cat_id])) {
$html .= $category['categories'][$cat_id]['category_link'] . "<br/>";
}
if (isset($category['parent_cats'][$cat_id])) {
$html .= $category['categories'][$cat_id]['category_link'];
$html .= buildcat($cat_id, $category);
}
}
}
return $html;
}
I guess my problem is because I'm getting only the info from DB for selected category ID, instead of getting all categories with parent_id that belongs to that category. I'm having headaches with this. Can you please help me? Thanks!