foreach data while inside?
Good afternoon, everybody. I have a doubt.
I have a WHILE, and accurate list of the data within it FOREACH . Does anyone know how to do this?
I would be very grateful for the help.
Example code.
$UserIDS= array();
$query->execute();
while ($lista = $query->fetch()){
$mensagem = $lista['mensagem'];
$UserIDS[] = $lista['idUser'];
echo
'
//Data from Forech, was shown here.
<div class="avatar"></div>
<div class="text">
'.utf8_encode($mensagem).'
</div>
';
}
//FOREACH data has to list before the $message, if put into the forech WHILE not sure of the fact that I have an array inside.
foreach ($UserIDS as $idUsua) {
echo "<div class='avatar'>".box::avatar($idUsua)."</div>";
}
Anyone know how do I pull data from FOREACH and put insid开发者_如何学Pythone the in WHILE? be very grateful for the help.
Referring to my earlier answer to your other question:
// fetch all the data in one go
$query->execute();
$data = $query->fetchAll();
// and then iterate it
foreach ($data as $lista) {
echo "<div id='avatar'>" . box::avatar($lista['idUser']) . "</div>";
echo "<div class='text'>" . utf8_encode($lista['mensagem']). "</div>";
}
Your existing box::avatar
call is then still free (as before) to make separate PDO query calls.
why don't you take this part
foreach ($UserIDS as $idUsua) {
echo "<div class='avatar'>".box::avatar($idUsua)."</div>";
}
into a function like
function userId($UserIDS){
$userAvatarDivs="";
foreach ($UserIDS as $idUsua) {
$userAvatarDivs.= "<div class='avatar'>".box::avatar($idUsua)."</div>";
}
return $userAvatarDivs;
}
and call it on
while ($lista = $query->fetch()){
$mensagem = $lista['mensagem'];
$UserIDS[] = $lista['idUser'];
echo
'
//Data from Forech, was shown here.
<div class="avatar"></div>
<div class="text">
'.utf8_encode($mensagem).'
</div>
'.userId($UserIDS);
}
精彩评论