duankuang7928 2012-09-26 08:04
浏览 133
已采纳

PHP嵌套的foreach循环:其中的html表

I need my PHP page to show the following structure:

  <table border="1">
  <tr>
         <td>Title one</td><td>Title two</td>
  </tr>
  <tr>
         <td>I'm content one</td><td>And here's content two</td>
  </tr>
  </table>

And here’s my php page:

$array = array( array( Title => "Title one"), array( Title => "Title two") );
$array2 = array( array( Content => "I'm content one"), array( Content => "And here's content two") );
 $myvar ="Title one";

$htm .="<table border='1'>";
    for ($i=0; $i<=1; $i++) 
    {
        $htm .="<tr>";
        foreach ($array[$i] as $title)
        {   
            $htm .="<td >".$title."</td>"; 
            foreach($array2 as $b)
            {
                $content  = $b['Content'];
                    if ($myvar == $title)
                    {
                        $htm .="<tr><td>".$content."</td></tr>"; 
                    }else
                    {
                        $htm .="<tr><td ></td></tr>"; 
                    }

            } 
        }
    }

$htm .="</table>";
echo $htm;

Which is outputting:

<table border='1'>
<tr>
<td >Title one</td><tr><td>I'm content one</td>
</tr>
<tr>
<td>And here's content two</td></tr>
<tr><td >Title two</td><tr>
<td></td></tr><tr><td ></td></tr>
</table>

How can I modify the html outputs to get the structure I need?

  • 写回答

3条回答 默认 最新

  • duanhaodi4809 2012-09-26 08:11
    关注

    Try this code, I hope this is what you want:

    $array = array( array( Title => "Title one"), array( Title => "Title two") );
    $array2 = array( array( Content => "I'm content one"), array( Content => "And here's content two") );
    
    $htm .="<table border='1'>";
        for ($i=0; $i<=1; $i++) 
        {
            $htm .="<tr>";
            foreach ($array[$i] as $title)
            {   
                $htm .="<td >".$title."</td>"; 
                $j=0;
                foreach($array2 as $b)
                {
    
                    $content  = $b['Content'];
                        if ($j == $i)
                        {
                            $htm .="<td>".$content."</td></tr>"; 
                        }
                        $j++;
    
                } 
            }
        }
    
    $htm .="</table>";
    echo $htm;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 速帮,学校需要在外上班没空
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义