简体   繁体   English

搜索列,以逗号分隔

[英]Search column with comma separated string

Currently I am using the query below together with a recursive function to print a menu. 目前,我正在使用下面的查询以及递归函数来打印菜单。

"SELECT * FROM categories WHERE FIND_IN_SET('".$parent."', parentId)"

DB structure: 数据库结构: 在此处输入图片说明

The result by printing this out is: 打印出来的结果是:

Smycken
--| Halsband
--|--| Guld
--|--|--| test
--|--|--|--| test2
--|--| Silver
--| Armband
Honung

Row 10, parentId . 第10行, parentId I got two values separated with a comma (I've read that this is not the ultimate way to store values, but I'll do it anyway), now I want row 10 to be printed out like a subcategory, just like my other rows are being printed out. 我用逗号分隔了两个值(我读过这不是存储值的最终方法,但是无论如何我都会这样做), 现在我希望第10行像子类别一样打印出来,就像我的其他子类别一样行被打印出来。 The solution I found was to use FIND_IN_SET or use LIKE, I get neither of them to work as I wish... 我发现的解决方案是使用FIND_IN_SET或使用LIKE,但我都不希望它们都起作用。

Suggestions or a solution for my problem? 对我的问题的建议或解决方案?

This is my function: 这是我的功能:

function getSubCat($level = 0, $parent = 0)
{                                               


$hasChildren = false;
$outputHtml = '%s';
$childrenHtml = '';

$dbh = getdbh();

$getSubCategory = $dbh->prepare("SELECT * FROM categories WHERE FIND_IN_SET('".$parent."', parentId)");
$getSubCategory->execute();
$categories = $getSubCategory->fetchAll();
foreach($categories as $category)
{

    if ($category['parentId'] == $parent) {
        $hasChildren = true;
        $childrenHtml .= '<option value="'.$category['id'].'">';

        for($k = 0 ; $k < $level; $k++) {
            $childrenHtml .= '--|';
        }

        $childrenHtml .= ' '.$category['name'];
        $level++;
        $childrenHtml .= '</option>';
        $childrenHtml .= getSubCat($level, $category['id']);         
        $level--;                                                       
    }
}

if (!$hasChildren) {
    $outputHtml = '';
}

    return sprintf($outputHtml, $childrenHtml);
}

Change this line: 更改此行:

if ($category['parentId'] == $parent) {

to: 至:

if (in_array($parent, explode(',', $category['parentId']))) {

The == test won't look for an element in a comma-separated string. ==测试不会在逗号分隔的字符串中查找元素。

Actually, you don't need this if at all. 其实,你并不需要这个if在所有。 The WHERE clause in the SQL already guarantees that $parent is in $category['parentId'] . SQL中的WHERE子句已经保证$parent$category['parentId']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM