2014-09-10 80 views
0

我正在尝试为游戏做一个工艺计算器。工艺计算器循环

我有一个数据库,谁是这样的:

工艺品:

id item_id item_name amount 
3  1895   a   5 
8  2486   c   1 

Craft_materials:

id craft_id item_id item_name amount 
1  3  2486   c   15 
2  3  5302   d   23 
3  3  5698   e   2 
4  8  2014   f   3 

这里是我的查询检索数据:

$craftProduct = $db->query("SELECT * FROM crafts WHERE item_id=$item"); 
$craftProduct->setFetchMode(PDO::FETCH_OBJ); 
$product = $craftProduct->fetch(); 

$craftID = $product->id; 

$craftMaterial = $db->query("SELECT * FROM craft_materials WHERE craft_id=$craftID"); 
$craftMaterial->setFetchMode(PDO::FETCH_OBJ); 

echo '<ul>'; 
    echo '<li>'.$product->item_name.' ('.$product->amount.')</li>'; 
     echo '<ul>'; 
     while($material = $craftMaterial->fetch()){ 
      echo '<li>'.$material->item_name.' ('.$material->amount.')</li>'; 
     } 
     echo '</ul>'; 
echo '</ul>'; 

我想要做的是取材料ID并检查它是否与工艺相符。如果是这样,我想展示制作它所需的材料。

我想要的东西,看起来像这样:

- a (5) 
    - c (15) 
     - f (3) 
    - d (23) 
    - e (2) 

不过,我不知道该怎么办的循环。谁能帮我?

回答

0

这是一个基本的递归设置:

function render_item($item_id) { 
    $product = fetch_item($item_id); // select from crafts where item_id = $item_id 
    $children = ""; 
    foreach (fetch_children($product->id) as $child_id) { // select from craft_mats where craft_id = $product->id 
     $children .= render_item($child_id); 
    } 
    echo "<li>" . $product->item_name . "<ul>" . $children . "</ul></li>"; 
} 

echo "<ul>" . render_item(1895) . "</ul>"