开发者

PHP how to display multiple array values

开发者 https://www.devze.com 2023-01-13 09:45 出处:网络
How can I display array values that I retrieved from the database for example the following array values.

How can I display array values that I retrieved from the database for example the following array values.

while($row = mysqli_fetch_array($query)){
    $post_id[] = $row['id'];
    $post_user_id[] = $row['user_id'];
    $post_title[] = $row['title'];
}

Output.

<li><a href="' . $post_user_id . 'post.php?id="' . $p开发者_如何学Cost_id . '">' . $post_title . '</a></li>
<li><a href="' . $post_user_id . 'post.php?id="' . $post_id . '">' . $post_title . '</a></li>
<li><a href="' . $post_user_id . 'post.php?id="' . $post_id . '">' . $post_title . '</a></li>
<li><a href="' . $post_user_id . 'post.php?id="' . $post_id . '">' . $post_title . '</a></li>
<li><a href="' . $post_user_id . 'post.php?id="' . $post_id . '">' . $post_title . '</a></li>


You can do the following outside the while loop:

for($i=0;$i<count($post_id);$i++) {
    echo '<li><a href="'.$post_user_id[$i].'post.php?id='.$post_id[$i].'">'.$post_title[$i] . '</a></li>';
}


<?
$data = array();
while($row = mysqli_fetch_array($query)){
  $data[] = $row;
}
?>

Output.

<? foreach ($data as $row): ?>
<li>
 <a href="<?=$row['post_user_id']?>post.php?id=<?=$row['post_id']?>">
  <?=$row['post_title']?>
 </a>
</li>
<? endforeach ?>


for ($i=0; $i<sizeof($post_id); $i++) {
   echo '<li><a href="' . $post_user_id[$i] . 'post.php?id=' . $post_id[$i] . '">' 
   . $post_title[$i] . '</a></li>';
}


while($row = mysqli_fetch_array($query)){
    $post_id = $row['id'];
    $post_user_id = $row['user_id'];
    $post_title = $row['title'];
    echo "<li><a href=\"" . $post_user_id . "post.php?id=" . $post_id . "\">" . $post_title . "</a></li>";
}

But in my Oppinion, the Links are not very well formated, you would need a [userid]post.php for each user. Better would be:

    echo "<li><a href=\""post.php?userid=\"".$post_user_id."\"&id=". $post_id ."\">" . $post_title . "</a></li>";

So your post.php gets the userid and the id per GET by clicking on the link.


Instead of splitting up a database record (a row) across multiple variables, it's usually a better idea to keep them together in a multi-dimensional array like this:

$posts = array();

while ($row = mysqli_fetch_array($query)) {
    $posts[] = $row;
}

foreach ($posts as $post) {
    echo $post['id'];
    echo $post['user_id'];
    echo $post['title'];
    ...
}


Better way would be

while($row = mysqli_fetch_array($query)){
   echo '<li><a href="' . $row['user_id'] . 'post.php?id="' . $row['id'] . '">' . $row['title'] . '</a></li>';
}

if you need the same output. But in my opinion the links are not well formed.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号