2010-03-07 10 views
8

Ecco cosa sto cercando di fare: - ho bisogno di una funzione che quando viene passato come argomento un ID (per una categoria di cose) fornirà tutte le sottocategorie e le sottocategorie -sub categorie e sub-sub-sub..etc. - Stavo pensando di utilizzare una funzione ricorsiva in quanto non so il numero di sottocategorie loro sotto-sottocategorie e così via ecco quello che ho cercato di fare finorafunzione ricorsiva per ottenere tutte le categorie figlio

function categoryChild($id) { 

    $s = "SELECT * FROM PLD_CATEGORY WHERE PARENT_ID = $id"; 
    $r = mysql_query($s); 

    if(mysql_num_rows($r) > 0) { 

     while($row = mysql_fetch_array($r)) 
      echo $row['ID'].",".categoryChild($row['ID']); 
    } 
    else { 
     $row = mysql_fetch_array($r); 
     return $row['ID']; 
    } 
} 

Se uso return invece di echo, non otterrò lo stesso risultato. Ho bisogno di aiuto per risolvere questo problema o riscriverlo da zero

risposta

12

Ho avuto difficoltà a cercare di capire la vostra funzione. Penso che questo farà quello che vuoi. Ottiene tutti i bambini di una categoria con ID $ id e anche i loro figli (ottenendo così l'intera sotto categoria, l'effetto sub sotto categoria che si desidera).

function categoryChild($id) { 
    $s = "SELECT ID FROM PLD_CATEGORY WHERE PARENT_ID = $id"; 
    $r = mysql_query($s); 

    $children = array(); 

    if(mysql_num_rows($r) > 0) { 
     # It has children, let's get them. 
     while($row = mysql_fetch_array($r)) { 
      # Add the child to the list of children, and get its subchildren 
      $children[$row['ID']] = categoryChild($row['ID']); 
     } 
    } 

    return $children; 
} 

Questa funzione restituisce:

$var = array(
     'categoryChild ID' => array(
       'subcategoryChild ID' => array(
         'subcategoryChild child 1' => array(), 
         'subcategoryChild child 2' => array() 
       ) 
     ), 
     'anotherCategoryChild ID' => array() # This child has no children of its own 
); 

Si restituisce essenzialmente un array con l'ID del bambino e un array contenente gli ID dei suoi figli. Spero che questo sia di qualche aiuto.

+0

Grazie anche a me – Umair

4

database tree to multidimensional array

<?php 
function getTree($rootid) 
{ 
    $arr = array(); 

    $result = mysql_query("select * from PLD_CATEGORY where PARENT_ID='$rootid'"); 
    while ($row = mysql_fetch_array($result)) { 
    $arr[] = array(
     "Title" => $row["Title"], 
     "Children" => getTree($row["id"]) 
    ); 
    } 
    return $arr; 
} 
?> 
1
function categoryChild($id) 
{ 
    $s = "SELECT category_id,name FROM proads_categories WHERE parent_id =".$id;  
    $r = mysql_query($s); 
    $children = array(); 
    if(mysql_num_rows($r) > 0) 
    { 
     #It has children, let's get them. 
     while($row = mysql_fetch_array($r)) 
     {   
      #Add the child to the list of children, and get its subchildren 
      $children[$row['category_id']]['nam'] = $row['name']; 
      $arr = categoryChild($row['category_id']); 
      if(count($arr) > 0) 
      { 
       $children[$row['category_id']]['child'] = categoryChild($row['category_id']); 
      } 
     } 
    } 
    return $children; 
} 

E 'perfetto. Se avete bisogno, per favore provate questo

4

Come questo è stato sollevato da @Pawan Sharma, ho pensato che potrei dare qualche risposta pure.

Tutte le soluzioni fornite soffrono di un problema comune: eseguono query SQL per ogni bambino. Ad esempio, se ci sono 100 bambini al 2 ° livello, verranno effettuate 100 query, mentre può essere effettivamente eseguita nella query singola utilizzando where parent_id in (<list_of_ids>).


Esempio DB:

create table category (
    id   int auto_increment primary key, 
    parent_id int default null, 
    title  tinytext, 
    foreign key (parent_id) references category (id) 
) engine = InnoDB; 

insert into category (id, parent_id, title) values 
    (1, null, '1'), 
    (2, null, '2'), 
    (3, null, '3'), 
    (4, 1 , '1.1'), 
    (5, 1 , '1.2'), 
    (6, 1 , '1.3'), 
    (7, 4 , '1.1.1'), 
    (8, 4 , '1.1.2'), 
    (9, 7 , '1.1.1.1'); 

Ecco la mia soluzione:

/** 
* @param null|int|array $parentID 
*/ 
function getTree($parentID) { 
    $sql = "select id, parent_id, title from category where "; 
    if (is_null($parentID)) { 
     $sql .= "parent_id is null"; 
    } 
    elseif (is_array($parentID)) { 
     $parentID = implode(',', $parentID); 
     $sql .= "parent_id in ({$parentID})"; 
    } 
    else { 
     $sql .= "parent_id = {$parentID}"; 
    } 

    $tree = array(); 
    $idList = array(); 

    $res = mysql_query($sql); 
    while ($row = mysql_fetch_assoc($res)) { 
     $row['children'] = array(); 
     $tree[$row['id']] = $row; 
     $idList[] = $row['id']; 
    } 
    mysql_free_result($res); 

    if ($idList) { 
     $children = getTree($idList); 
     foreach ($children as $child) { 
      $tree[$child['parent_id']]['children'][] = $child; 
     } 
    } 
    return $tree; 
} 

Con i dati di esempio forniti, lo fa al massimo 5 query, quando viene chiamato come getTree(null) (per tutti voci):

select id, parent_id, title from category where parent_id is null 
select id, parent_id, title from category where parent_id in (1,2,3) 
select id, parent_id, title from category where parent_id in (4,5,6) 
select id, parent_id, title from category where parent_id in (7,8) 
select id, parent_id, title from category where parent_id in (9) 

Quando viene chiamato come getTree(4), 3 query vengono eseguiti:

select id, parent_id, title from category where parent_id = 4 
select id, parent_id, title from category where parent_id in (7,8) 
select id, parent_id, title from category where parent_id in (9) 
1
function breadCrumb($id) 
{ 
    $ar = array(); 
    $result = mysql_query("SELECT * FROM groups WHERE ParentID = '$id'"); 
    if(mysql_num_rows($result) > 0) 
    { 
     while($row = mysql_fetch_object($result)) 
     { 
      $ar[] = $row->DBGroupID; 
      $r = mysql_query("SELECT * FROM groups WHERE ParentID = '".$row->GroupID."'"); 
      if(mysql_num_rows($r) > 0) 
       $ar = array_merge($ar, breadCrumb($row->GroupID, 1)); 
     } 
    } 
    return $ar; 
} 
0

Utilizzando la funzione Prestashop:

public function getRecursiveChildren() { 

    $subCategories = $this->recurseLiteCategTree(); 
    //print_r($subCategories); 


    $my_tab = array(); 

    foreach ($subCategories['children'] as $subc) { 
     $my_tab[] = $subc['id']; 
     foreach ($subc['children'] as $subc2) { 
      $my_tab[] = $subc2['id']; 
      foreach ($subc2['children'] as $subc3) { 
       $my_tab[] = $subc3['id']; 
       foreach ($subc3['children'] as $subc4) { 
        $my_tab[] = $subc4['id']; 
       } 
      } 
     } 
    } 
    $my_tab [] = $this->id; 

    return $my_tab; 
} 

questo può essere migliorata utilizzando ricorsività ma non c'è tempo per questo oggi: '(

1
<?php  
require('db/dbconnect.php'); 

$user_id='triD-100'; 
$sql="select * from ajent_joining where sponser_id='".$user_id."'"; 
$qR=mysql_query($sql); 
while($rowD=mysql_fetch_assoc($qR)){  
    echo $childId=$rowD["user_id"]; 
    echo "<br/>"; 
    categoryChild($childId);  
    } 

    function categoryChild($childId) { 

    $s = "select user_id from ajent_joining where sponser_id='".$childId."'"; 
    $r = mysql_query($s); 
    if(mysql_num_rows($r) > 0) { 

     while($row = mysql_fetch_array($r)) { 

      echo $childId=$row["user_id"]; 
      echo "<br/>"; 
      categoryChild($childId); 
    } 
} 

} 


?> 
Problemi correlati