twan twan - 4 months ago 7
PHP Question

Use exploded array as a list within a while loop

I got a while loop that shows some old data. I recently added a new tablerow to the database that contains a string thats exploded into an array at every comma.

I then use a for loop to show the array values into a list and use the variable that contains the list in the echoed while loop data.

My code (only relevant parts):

while($row_items = mysqli_fetch_array($res_items, MYSQLI_ASSOC)) {

if($row_items['checkpoints'] != ''){
$check = explode(',', $row_items['checkpoints']);
}else{
$check = '';
}

foreach($check as $list){
$checklist .= '<li>'.$list.'</li>';
}

echo '
<div class="col-lg-2 col-md-3 col-sm-6 col-xs-6 portf">
<a class="fancybox" href="../../catalogus/'.$row_items['afbeelding'].'">
<div class="gallery-item">
<div class="image">
<img src="../../catalogus_icons/'.$row_items['afbeelding'].'.jpg" alt="" style="border:1px solid #ccc;" class="img-responsive" />
</div>

<div class="bottom-info">
<div class="name">'.$row_items['naam'].'</div>
<div>'.$checklist.'</div>
<button class="contact_button buttoncontact btn-primary" style="border-radius:2px;">
Contact
<span class="icon-mail-alt"></span>
</button>
</div>
</div>
</a>
</div>';
}


But this shows the same list on every div output (while loop result). I added 1 list to test, and it adds that list to every item, not only the item that has a list. How can I make sure it only adds the list to the correct result?

$row_items['checkpoints'];
contains: 'goedkoop,snel,test'

Answer

It's likely because you are not clearing the $checklist variable between iterations of the loop. You are simply adding to the same list every iteration.

while ($row_items = mysqli_fetch_assoc($res_items)) {

    $checklist = '';
    if ($row_items['checkpoints'] != '') {
        $check = explode(',', $row_items['checkpoints']);
        foreach($check as $list) {
            $checklist .= '<li>'.$list.'</li>'; 
        }
    }

    echo '
    <div class="col-lg-2 col-md-3 col-sm-6 col-xs-6 portf">
      <a class="fancybox" href="../../catalogus/'.$row_items['afbeelding'].'">
        <div class="gallery-item">
            <div class="image">
                <img src="../../catalogus_icons/'.$row_items['afbeelding'].'.jpg" alt="" style="border:1px solid #ccc;" class="img-responsive" />
            </div>

            <div class="bottom-info">
                <div class="name">'.$row_items['naam'].'</div>
                <div>'.$checklist.'</div>
                <button class="contact_button buttoncontact btn-primary" style="border-radius:2px;">
                    Contact
                    <span class="icon-mail-alt"></span>
                </button>
            </div>
        </div>
        </a>
    </div>';
}