php函数创建包含所有类别和子类别ides的数组

时间:2015-03-01 14:03:32

标签: php arrays

我写了一个函数来创建一个包含category_id和所有子类别ides的数组,主要类别应该从页面中选择url example pages.php?category_id = 1,

然后数组应该像1,23,25

“25是父23的子类别,23是1”的子类别,

我稍后会用它来显示数组示例中存在item_cat的项目

SELECT * FROM items WHERE item_cat IN (1,23,25)

问题是我的功能是在页面中回显,我不确定我是否以正确的方式编写了这里是我的功能代码

$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);

1 个答案:

答案 0 :(得分:1)

可能试试这个:

<?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;

?>