如何循环它们?

时间:2013-03-10 20:07:59

标签: php mysql wordpress

如果结构是:

parent A
  -child B
   - - child c
  ---child d
----child e

以下代码可以循环第一层(-child B)。如果我想将它们全部循环出去,我该怎么做?

foreach ($childCatID as $kid)
{
    $childCatName = $wpdb->get_row("SELECT name FROM $wpdb->terms WHERE term_id=$kid");
    echo $childCatName->name;
}

如果父A中所有孩子的图层是第四深度,如何将它们循环出去? 如果父A中所有孩子的层都不知道,有没有办法将它们循环出去?

我尝试使用以下代码,但没有将它们循环出来。

foreach ($childCatID as $kidone)
  foreach ($kidone as $kidtwo){
    foreach ($kidtwo as $kidthree){
      foreach ( $kidthree as $kid){
        $childCatName = $wpdb->get_row("SELECT name FROM $wpdb->terms WHERE term_id=$kid");
        echo $childCatName->name;
      }
    }
}

1 个答案:

答案 0 :(得分:0)

您应该将foreach循环打包到函数中,并以递归方式调用它

function EchoNode($node)
{
    if (is_array($node))
    {
        foreach ($node as $kid)
        {
            if (is_array($kid))
            {
                EchoNode($kid);
            }
            else
            {
                $childCatName = $wpdb->get_row("SELECT name FROM $wpdb->terms WHERE term_id=$kid");
                echo $childCatName->name;
            }
        }
    }
    else
    {
        $childCatName = $wpdb->get_row("SELECT name FROM $wpdb->terms WHERE term_id=$node");
        echo $childCatName->name;
    }
}