2013-09-05 20 views
0

我試着動態獲取產品的子ID。下面是我的表結構。動態從數據庫中獲取子ID?

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

上午要通過只有一個父ID並獲得子ID,如果再有孩子的孩子ID的人,那麼我必須獲取該記錄also.example 44-> 35,6,47,在這個47和50中有5,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。 誰能幫助我做到這一點..

+0

你只想刪除重複? ['array_unique'](http://php.net/manual/en/function.array-unique.php)應該做的訣竅...如果你有一個字符串,使用'explode(',',$ string) '先獲得一個數組。 – naththedeveloper

+2

切勿將多條信息存儲在單個字段中。它會一直導致你的問題。 – Basic

回答

3

你的數據庫結構優化的心不是這個,這將是更好的:

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 

這被稱爲樹結構,應該給這樣的事情:
- 2
- - 4
- - 5
- 3
在這個例子中我使用用於顯示目的的回波,則可以通過一個陣列,相同的原理


返回值要回答好一點,你當前的結構可以支持類似的方法,但是因爲你使用了字符串,所以它會變得更慢,並且不太靈活。您可以看到您使用的代碼與我剛纔使用的數量的差異。如果你將刪除回聲,並只返回陣列,它會更小:) :)