Guillaume Wagner Guillaume Wagner - 1 month ago 10
PHP Question

For each inside other for each on view MVC PHP

I'm trying to give structure to my code and i am facing a problem.
I'm looping through a sql query response and for each element i'm trying to retrieve other related elements. It works in my controller without problem but when i'm trying to repeat in the view I always get the same value for the related element

My controller:

<?php
include_once('class/guide.class.php');
$bdd = new DBHandler();
$req = guide::getGuides($bdd,0,5);


foreach ($req as $results => $poi)
{
$req[$results]['id'] = htmlspecialchars($poi['id']);;
$req[$results]['name'] = nl2br(htmlspecialchars($poi['name']));

$guide = new guide($results['name'],$bdd);
$guidePois = $guide->getGuidePois($poi['id']);
foreach ($guidePois as $res => $re)
{
echo $guidePois[$res]['id'];
echo $guidePois[$res]['name'];
$guidePois[$res]['id'] = htmlspecialchars($re['id']);
$guidePois[$res]['name'] = nl2br(htmlspecialchars($re['name']));
}
}

include_once('listing.php');


here, you see that I echo the ids/names of the related list of element and it works well, the output is correct for each element of the first list.

When i do it in my view:

<?php
foreach($req as $poi)
{
?>
<div class="news">
<h3>
<?php echo $poi['id']; ?>
<em>: <?php echo $poi['name']; ?></em>
</h3>
<?php foreach($guidePois as $re)
{
?>
<h4>
<?php echo $re['id']; ?>:
<?php echo $re['name']; ?>
</h4>
<?php
}
?>
</div>
<?php
}
?>


Somehow the first list output are the good elements, but for the 2nd list, i always get the related elements of the first item.

Do you have an idea ?

Thanks a lot for your help

Answer

This is because you only set:

$guidePois = $guide->getGuidePois($poi['id']);

once in the controller.

If you want it to work in the view, you need to insert this code right after the closing </h3>

<?php $guidePois = $guide->getGuidePois($poi['id']); ?>

So that $guidePois gets a new value in each iteration.

Complete view code:

<?php
foreach($req as $poi)
{
?>
<div class="news">
    <h3>
        <?php echo $poi['id']; ?>
        <em>: <?php echo $poi['name']; ?></em>
    </h3>
    <?php 
    $guidePois = $guide->getGuidePois($poi['id']);
    foreach($guidePois as $re)
    { 
        ?>
        <h4>
        <?php echo $re['id']; ?>:
        <?php echo $re['name']; ?>
        </h4>
    <?php 
    } 
    ?>
</div>
<?php
}
?>
Comments