PHP技术问询:如何读取数据库多维数组并合并数组?
嘿,我来帮你捋捋这段代码的问题哈~
你现在的逻辑是每读取一条数据库记录就立刻检查数组,但这时候$datas还在逐步收集数据,可能还没攒齐所有masa值就提前判断了,而且循环里的print_r($datas)会每次循环都打印一遍数组,这就是你看到多次Array ([0]...)输出的原因。
修正后的代码
// 数组声明 $datas = array(); if(mysqli_num_rows($result) > 0) { // 先把所有数据库里的masa值都收集到数组里 while($row = mysqli_fetch_assoc($result)) { $datas[] = $row['masa']; } // 等所有数据收集完,再判断是否同时存在Pagi和Petang if(in_array("Pagi", $datas) && in_array("Petang", $datas)) { echo " <tr> <td>Sudah ditempah </td> <td>Sudah ditempah</td> <td>Sudah ditempah</td> </tr>"; } // 如果需要查看最终的数组内容,把print_r放在这里就行 // print_r($datas); }
为啥这么改?
- 先完成所有数据的收集,再做判断,确保不会因为数据没攒全导致判断失误
- 把
print_r移到循环外,避免重复输出数组内容 - 逻辑更清晰,后续要扩展其他判断条件也更方便
内容的提问来源于stack exchange,提问作者Hasifah Hassan
相关产品推荐
相关产品推荐

