Reputation: 113
i wrote a function to create an array with category_id and all subcategories ides, the main category should be selected from the page url example pages.php?category_id = 1,
then the array should be like 1,23,25
"25 is a subcategory for parent 23 and 23 is a subcategory for 1",
i'll use this later to show items with item_cat exist in array example
SELECT * FROM items WHERE item_cat IN (1,23,25)
the problem is my function is echo in the page, and i'm not sure i wrote it in a correct way here is my function code
$category_id=$_REQUEST['category_id'];
function categoriesIdes($parentId, $connection) {
global $category_id;
$sqlCategories = "SELECT * FROM categories
WHERE category_parent = ".$parentId." ";
$rsCategories = mysql_query($sqlCategories, $connection);
$totalCategoriesRows = mysql_num_rows($rsCategories);
while($rowsCategories = mysql_fetch_assoc($rsCategories)) {
$catId = $rowsCategories['category_id'];
echo ''.$catId.',' ;
categoriesIdes($catId, $connection);
}
}
$ides = categoriesIdes($category_id, $connection);
$idesall = ''.$category_id.','.$ides.'';
$idesall = substr($idesall,0,-1);
Upvotes: 0
Views: 649
Reputation: 1220
Possibly try this:
<?php
$category_id=$_REQUEST['category_id'];
function categoriesIdes($parentId, $connection) {
//not sure why you're using this
global $category_id;
//select all the childeren
$sqlCategories = "SELECT * FROM categories
WHERE category_parent = ".$parentId." ";
//query
$rsCategories = mysql_query($sqlCategories, $connection);
$totalCategoriesRows = mysql_num_rows($rsCategories);
//will hold categoryIDs found
$categoryIDs = array();
//for every child
while($rowsCategories = mysql_fetch_assoc($rsCategories)) {
//child id
$catID = $rowsCategories['category_id'];
//add to array
$categoryIDs[] = $catID;
//debug
echo ''.$catID.',' ;
//find and add the childeren
$categoryIDs = array_merge($categoryIDs, categoriesIdes($catID, $connection));
}
return $categoryIDs;
}
$ides = categoriesIdes($category_id, $connection);
$ids = '';
if (count ($ides) > 0){
$ids = $category_id .','. implode(',',$ides);
}
else{
//only 1 id
$ids = $category_id;
}
echo $ids;
?>
Upvotes: 1