douchigu1723 2016-07-10 17:28
浏览 62
已采纳

在for循环返回Null中迭代数组

<?php
//Called at start of page
while( $row = mysqli_fetch_assoc($result)){
    $dataset[] = $row;
}

//Called in middle of page, inside <table><tbody>
$dSize = count($dataset);
for( $i = 0; $i < $dSize; $i++){
//foreach($dataset as $row){
    $row = $dataset[$i];
    $thisIsId = true;
    echo "<tr>";
    $rSize = count($row);
    for( $j = 0; $j < $rSize; $j++){
    //foreach($row as $value){
        $value = $row[$j];
        //Next line output ex: <td id='r1c2' class='editable'>Bob
        echo "<td id='r$i" . "c$j'" . ($thisIsId ? "" : " class='editable'")  . ">$value";
        $thisIsId = false;
    }
}
?>

I'm trying to fill out a table that contains customer information, but $value keeps returning null. The foreach loops that are commented out are left there because these loops worked except I wasn't able to assign an id to the element based on $i and $j (obviously).

If I add a console.log of json_encode($row) after the line $row = $dataset[$i];, I get a JSON object that has all of the values filled out appropriately. As soon as I go into the nested for loop, I keep getting null values for $value AND $row[$j] if I just call that directly.

The ternary operator exists to check if it's the first column (the ID column) because that's the only cell that is not editable.

I've tried using global $row because I ran into a problem with scope in PHP before but it didn't seem to solve anything. I also tried renaming the $row variable to make sure it wasn't a conflict with when I use $row at the beginning of the page, but that also didn't solve anything.

tl;dr Why is $value returning null when used in a for loop but not when used in a foreach loop?

</div>
  • 写回答

2条回答 默认 最新

  • dongyi2534 2016-07-10 17:35
    关注

    mysqli_fetch_assoc returns an associative array and not an ordered array : http://php.net/manual/en/mysqli-result.fetch-assoc.php.

    So the key are the name of the column in your table that's why you cannot loop over it using a for loop. Use a foreach loop instead.

    You should have a E_NOTICE error raised (Undefined index) in your nested loop.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵