如果我的数组索引'如何使用foreach获取表数据?是相同的

时间:2016-09-11 07:52:34

标签: php mysql arrays

$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 }?>

1 个答案:

答案 0 :(得分:1)

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

$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设置中的视图),则第一个循环应如下所示:

$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
}