0

如果结构是:

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;
      }
    }
}
4

1 回答 1

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;
    }
}
于 2013-03-10T20:27:43.090 回答