【问题标题】:getting child id's from database dynamically?动态地从数据库中获取子 ID?
【发布时间】:2013-09-05 11:40:47
【问题描述】:

我尝试动态获取产品的子 ID。下面是我的表结构。

parent|child
---------------------
44    | 35,6,47,5,50
---------------------
47    | 8,9
---------------------
50    | 12, 15

我将只传递一个父 ID 并获取子 ID,如果任何一个子 ID 有另一个孩子,那么我也必须获取该记录。示例 44->35,6,47,5,50 在这 47 和 50 有子 ID,所以我的最终输出应该是这样的 44-> 35,6,47,8,9,5,50,12,15。

我在下面试过了,

$sql=mysql_fetch_assoc(mysql_query("select * from chain_product where parent='44'"));
$parent=$sql['parent'];
$child=$sql['child'];
$ex=explode(",",$child);
$count=sizeof($ex);
for($i=0;$i<$count;$i++)
{
$list=add_child($ex[$i],$child);
$check=explode(",",$list);
$chck_count=sizeof($check);
if($chck_count>$count)
    {
            $exit=add_child($ex[$i],$list);
            print_r($exit);
    }
}

function add_child($main,$ch)
{
$find=mysql_query("select * from chain_product where parent='$main'");
$res=mysql_fetch_assoc($find);
if($res)
{
$replace=$main.",".$res['child'];
$alter=str_replace($main,$replace,$ch);
 echo $alter;
 }
}

但我得到这样的结果,

35,6,47,8,9,5,5035,6,47,5,50,12,15

但我需要的输出应该是这样的.. 35,6,47,8,9,5,50,12,15。 谁能帮我做到这一点..

【问题讨论】:

  • 您只是想删除重复项? array_unique 应该可以解决问题...如果您有字符串,请先使用 explode(',', $string) 获取数组。
  • 永远不要在一个字段中存储多条信息。它总会给你带来麻烦。

标签: php mysql function


【解决方案1】:

你的数据库结构不是最适合这个,这样会更好:

id | parent
1  | 0
2  | 1
3  | 1
4  | 2
5  | 2

这样你可以做一些事情递归

function getChilds($parent=0, $depth=0){
    // Select the items for the given $parent
    $query = $conn->mysqli_query("SELECT id WHERE parent=".$parent); // mysqli is better, but mysql will do fine
   // get the items by the parent giving as input:
    while($fetch = $query->fetch_assoc() ){
        echo str_repeat('-', $depth) . " ".$fetch['id'];        
        getChilds($fetch['id'], $depth+1); // Use id of this line to find its childs
        echo "<br />";
    }
}
getChilds(0); // And start it. The 0 is optional, I personaly prefer -1. Whatever rows your boat

这称为树形结构,应该是这样的:
1
- 2
- - 4
- - 5
- 3
在这个例子中我使用回显来显示,你可以通过数组返回值,同样的原理


为了更好地回答,您当前的结构可以支持类似的方法,但由于您使用字符串,它会允许速度较慢且灵活性较差。您可以看到您使用的代码的差异,以及我刚刚使用的数量。如果您要删除回声并只返回数组,它会更小:)

【讨论】:

    猜你喜欢
    • 2017-11-26
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 2013-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多