Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/241.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php和codeigniter中的主类别+3级子类别_Php_Mysql_Codeigniter - Fatal编程技术网

php和codeigniter中的主类别+3级子类别

php和codeigniter中的主类别+3级子类别,php,mysql,codeigniter,Php,Mysql,Codeigniter,我有4个级别的表,如: +-------+---------------+---------------------------+ | id | sub_for | level | +-------+---------------+---------------------------+ | 1 | 0 | 1 | - main category | 2

我有4个级别的表,如:

+-------+---------------+---------------------------+
|   id  |     sub_for   |           level           |
+-------+---------------+---------------------------+
|   1   |       0       |             1             | - main category
|   2   |       1       |             2             | - first level
|   3   |       2       |             3             | - second level
|   4   |       3       |             4             | - third level
+-------+---------------+---------------------------+
我将有多个类别和子类别

因此,当我选择主类别级别1时,我需要选择所有子类别

我可以达到第二级,比如:

$findInIds = array();
$data['category'] = '1';
$query = $this->db->query('SELECT id FROM shop_categories WHERE sub_for = ' . $data['category']);

foreach ($query->result() as $row) {
    $findInIds[] = $row->id;
}
我得到了和所选主类别相关的所有子类别2级数组

Array
(
    [0] => 2

)

我想我应该使用一些递归函数循环到第四级,但我在这里迷路了…

所以,你走的是正确的道路,你需要遵循它。 您得到了第一个类别的检查结果,您需要检查它的子类,以及子类的子类

下面使用while循环代替递归。 我们将找到的每个子类别添加到下一步需要查看的子类别列表中。 然后我们检查每个子类别,并将任何新的子类别添加到列表中。 一旦我们检查了最后一个,while循环将结束。没有任何子级的类别

另外,由于从数组的末尾移除元素并添加到末尾,这实际上是一个过程,我们在检查树的同一级别之前先检查树

// Initialize arrays
$findInIds = [];
$idsToCheck = [];

// Load up First Category
$idsToCheck[] = '1';
while(count($idsToCheck)){
    // Grab a new category to check
    $idToCheck = array_pop($idsToCheck);

    // Make the query
    $query = $this->db->query('SELECT id FROM shop_categories WHERE sub_for = ' . $idToCheck); // TODO: use query sanitization or parameterized queries
    foreach ($query->result() as $row) {
        // Foreach Result ...
        // - Add to find in ids (This is a subcategory of the category we are checking)
        // - Add to ids to check (This subcategory may have subcategories itself)
        $findInIds[] = $row->id;
        $idsToCheck[] = $row->id;
    }
}