2017-02-16 76 views
2
<?php 
try { 
    $stmt2 = $db->query("SELECT cid, parent, name FROM category");    
    $row_count = $stmt2->rowCount(); 
    if ($row_count) { 
     $rows = $stmt2->fetchAll(PDO::FETCH_ASSOC);   
    } 

} catch (PDOException $e) { 
    echo $e->getMessage(); 
} 

$items = $rows; 
$id = ''; 
echo "<select>"; 
foreach ($items as $item) { 
    if ($item['parent'] == 0) { 
     echo "<option><a href='#'>".$item['name']."</a>"; 
     $id = $item['cid']; 
     sub($items, $id); 
     echo "</option>"; 
    } 
} 
echo "</select>"; 

function sub($items, $id){   
    foreach ($items as $item) { 
     if ($item['parent'] == $id) { 
      $x = '-'; 
      $x++;            
      echo "<option>".$x."<a href='#'>".$item['name']."</a>";   
      sub($items, $item['cid']); 
      echo "</option>";     
     } 
    }   
} 
?> 

这是我的下拉菜单代码。我想在每个父项中使用这个“ - ”字符,并在每个父项中自动递增该字符。 像这样选择菜单:Php如何自动递增字符?

enter image description here

回答

1

我认为你需要使用str_repeat()

例如:

foreach ($items as $item) { 
    if ($item['parent'] == 0) { 
     echo "<option><a href='#'>".$item['name']."</a>"; 
     $id = $item['cid']; 
     sub($items, $id, 1); 
     echo "</option>"; 
    } 
} 
echo "</select>"; 

function sub($items, $id, $counter){  
    foreach ($items as $item) { 
     if ($item['parent'] == $id) {         
      echo "<option>".str_repeat("-",$counter)."<a href='#'>".$item['name']."</a>";   
      sub($items, $item['cid'],$counter+1); 
      echo "</option>"; 
     } 
    }   
} 
+0

好了,感谢,但它不是很贝尔工作。 –

+0

@Bilgehan可以,现在有什么问题? – Mohammad

+0

它将这个“ - ”字符添加到错误的父母身上。 –