gpt4 book ai didi

php - 如果我的数组索引相同,如何使用 foreach 获取表数据

转载 作者:行者123 更新时间:2023-11-29 11:18:00 25 4
gpt4 key购买 nike

$query = mysqli_query($con,"SELECT id,title,post FROM titlepost");

$data = [];

while($row = mysqli_fetch_assoc($query))
{
$data = $row;
var_dump($data);
}

通过这段代码我得到

array(3) { ["id"] => string(1) "1" ["title"] => string(4) "News" ["post"] => string(21) "Here can be your news"
}

array(3) { ["id"] => string(1) "4" ["title"] => string(5) "Maths" ["post"] => string(30) "Here can be your maths' theory"
}

array(3) { ["id"] => string(1) "5" ["title"] => string(6) "Toyota" ["post"] => string(26) "Here can be your car's add"
}

这里我想用foreach获取数据

<?php
foreach($data as $value) { ?>
<tr>
<th><?=$value['id']?></th>
<th><?=$value['title']?></th>
<th><?=$value['post']?></th>
</tr>
<?php }?>

最佳答案

无需使用两个单独的循环。您可以只输出第一个循环中的值:

$query = mysqli_query($con,"SELECT id,title,post FROM titlepost");

while($row = mysqli_fetch_assoc($query)) {
?><tr>
<th><?=$row['id']?></th>
<th><?=$row['title']?></th>
<th><?=$row['post']?></th>
</tr><?php
}

但是,如果您出于某种原因想要将结果存储在数组中(例如多次使用它或将其传递给 MVC 设置中的 View ),您的第一个循环应如下所示:

$query = mysqli_query($con,"SELECT id,title,post FROM titlepost");

$data = [];

while($row = mysqli_fetch_assoc($query))
{
$data[] = $row; // this line appends a new item to the $data array, instead of overwriting it, like in your original code
}

关于php - 如果我的数组索引相同,如何使用 foreach 获取表数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39433973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com