duanji1482 2016-02-13 10:45
浏览 31
已采纳

通过php中的数组循环

<?php
for($i=0; $i<sizeof($top_name); $i++)
{
  for($i=0; $i<sizeof($top_name); $i++)
  {
    echo "<tr><td>".$sub_name[$i]."</td><td>".$sub_diff[$i]."</td></tr>";
    echo "<tr><td>".$top_name[$i]."</td><td>".$top_diff[$i]."</td>  <td>".$top_size[$i]."</td></tr>";
  }
}

?> 

Error :

Notice: Undefined offset: 2 in C:\xampp\htdocs\TRY\data.php on line 28
Notice: Undefined offset: 2 in C:\xampp\htdocs\TRY\data.php on line 28

I'm trying to fetch arrays and arranging them in table but it is giving that error.

Please solve this. Thanks in advance...

  • 写回答

1条回答 默认 最新

  • dqk94069 2016-02-13 11:06
    关注

    Assuming you have these elements in $top_name and $sub_name array:

    $top_name = array( 'First Name', 'Second Name', 'Third Name', 'Fourth Name' );
    $sub_name = array( 'Sub One', 'Sub Two' );
    

    your two loops acts in this way:

    1) main loop    > $i = 0 > executed
    2)     2nd loop > $i = 0 > executed
    3)     2nd loop > $i = 1 > executed
    4)     2nd loop > $i = 2 > executed > undefined offset for $sub_name
    5)     2nd loop > $i = 3 > executed > undefined offset for $sub_name
    6) main loop    > $i = 4 > not executed
    

    So, the deeper loop is executed also for non-existent $sub_name elements, whereas the main loop is executed only once.

    In the second loop, you have to change incrementing variable name and condition variable:

    for( $i=0; $i<sizeof( $top_name ); $i++ )
    {
        for( $n=0; $n<sizeof( $sub_name ); $n++ )
        {
            echo "<tr><td>".$sub_name[$n]."</td><td>".$sub_diff[$n]."</td></tr>";
            echo "<tr><td>".$top_name[$i]."</td><td>".$top_diff[$i]."</td>  <td>".$top_size[$i]."</td></tr>";
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化