2010-10-15 5 views
3

J'ai une catégorie de nom de la table avec Col. suivantessous catégorie par table php et mysql

cat_id  | name  | parent 
1   | item 1 |  0 
2   | item 2 |  1 
3   | item 3 |  0 
4   | item 4 |  1 
5   | item 5 |  3 

Comment je peux l'afficher dans un menu comme celui-ci

Item 1 

    > Item 2 
    > Item 4 

Item 3 

    > Item 5 

S'il vous plaît aider

Répondre

2

ici est la fonction qui peut être utilisée:

// $current_cat_id: the current category id number 
// $count: just a counter, call it as 0 in your function call and forget about it 
// Gets the drop down list recurssively of categories // 

function find_pages_recursive($current_cat_id, $count) 
{ 
    global $db; // the database object instance 
    static $option_results; 

    // if there is no current category id set, start off at the top level (zero) 
    if (!isset($current_cat_id)) 
    { 
     $current_cat_id = 0; 
    } 

    $count++; 

    // query the database for the sub-categories of whatever the parent category is 
    $query = 'SELECT id, title from pages where parid = ' . $current_cat_id . ' order by id'; 

    $get_options = $db->execute($query); 
    $num_options = $db->count_select(); 

    // our category is apparently valid, so go ahead :P 
    if ($num_options > 0) 
    { 
     while (list($cat_id, $cat_name) = mysql_fetch_row($get_options)) 
     { 
      // if its not a top-level category, indent it to show that its a child category 
      if ($current_cat_id != 0) 
      { 
       $indent_flag = ''; 
       for ($x = 2; $x <= $count; $x++) 
       { 
        $indent_flag .= '----'; 
       } 

       $indent_flag .= ' '; 
      } 

      $option_results[$cat_id] = $indent_flag . $cat_name; 

      // now call the function again, to recurse through the child categories 
      find_pages_recursive($cat_id, $count); 
     } 
    } 

    return $option_results; 
} 

Comment l'utiliser:

echo '<select name="pages" id="pages">' . "\n"; 
echo '<option value="">--Select Page--</option>' . "\n"; 

$get_options = find_pages_recursive(0, 0); 

if (count($get_options) > 0) 
{ 
    foreach ($get_options as $key => $value) 
    { 
     $options .= "<option value=\"$key\""; 
     $options .= ">$value</option>\n"; 
    } 
} 

echo $options; 
echo '</select>' . "\n"; 

Assurez-vous de vous connecter à la première base de données :)

Questions connexes