在PHP中具有唯一名称的递归函数

时间:2014-11-25 15:30:16

标签: php wordpress recursion

1)我从下拉列表中选择了一只山羊,并且拥有goat_id和它的父亲和母亲这两个字段都是父母山羊名称。

2)我试着用goat_name递归调用它,为每个父系和大坝两个领域。

function generate_tree($goat_id) 
{
    global $wpdb;

    // get all records from database whose parent is $id
    $sql = $wpdb->prepare("SELECT * FROM mm_goats WHERE id = %d", $goat_id);
    $row2 = $wpdb->get_row($sql, ARRAY_A);

    //check if there are any results

        if(!empty($row2))
        {
            echo "<ul>";
            if($row2['sire'] != "" || $row2['dam'] != "")
            {
                //print result and call function to check if it has children
                echo "<li>Sire: ".$row2['sire']."</li>";
                echo "<li>Dam: ".$row2['dam']."</li>";
                generate_tree($row2['id']);
            }
            echo "</ul>";
        }
}

我使用了这个功能,它与第一个选择的父亲和大坝一起进入无限循环。

遵循此结构。 对于前: enter image description here

2 个答案:

答案 0 :(得分:-1)

$sql = $wpdb->prepare("SELECT * FROM mm_goats WHERE id = %d", $goat_id);
                                                    ^^^^^^^                          

您获取指示的ID,然后在recusrive调用中使用:

            generate_tree($row2['id']);
                          ^^^^^^^^^^^

因此,您只需在每次递归迭代时继续获取有关 SAME 山羊的信息。山羊#42 - &gt;山羊#42 - &gt;山羊#42等...直到你达到递归/内存限制。

您的递归调用应使用dam / sire ID:

  generate_tree($row['id_of_dam']);
  generate_tree($row['id_of_sire']);

代替。

#42 -> #7,10 -> #1,2,3,4 etc...

答案 1 :(得分:-1)

您应该将表格结构更新为

mm_goats
   - id
   - sire_id
   - dam_id
   - name

然后你可以做一个内连接来选择它们

SELECT `mm_goats`.`name`, `mm_goats`.`sire_id`, `mm_goats`.`dam_id`, `sire`.`name` AS `sire_name`, `dam`.`name` AS `dam_name`
    FROM `mm_goats`
        INNER JOIN `mm_goats` AS `sire` ON `mm_goats`.`sire_id` = `sire`.`id`
        INNER JOIN `mm_goats` AS `dam` ON `mm_goats`.`dam_id` = `dam`.`id`
    WHERE `mm_goats`.`id` = %d

之后,您可以启动递归

echo "<li>Sire: ".$row2['sire_name'];
generate_tree($row2['sire_id']);
echo "</li>";
echo "<li>Dam: ".$row2['dam_name'];
generate_tree($row2['dam_id']);
echo "</li>";