【问题标题】:php function to create array with all categories and subcategories idesphp函数创建包含所有类别和子类别ide的数组
【发布时间】:2023-03-14 15:49:01
【问题描述】:

我写了一个函数来创建一个包含 category_id 和所有子类别 ide 的数组,主类别应该从页面 url 示例 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);

【问题讨论】:

  • 您的类别级别有多深?
  • 没有限制用户可以添加类别和子类别只需要它循环直到 las 孩子(子类别)

标签: php arrays


【解决方案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;

?>

【讨论】:

  • 先生,我遇到了一个小麻烦,如果数组有多个数字示例 (1, 3) 可以正常工作,但如果它只有一个数字,则数组显示如下 (1,) 所以如果数组只包含一个数字,我怎么能得到额外的(,)?
猜你喜欢
  • 1970-01-01
  • 2021-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-20
  • 1970-01-01
相关资源
最近更新 更多