peter flanagan peter flanagan -4 years ago 63
HTML Question

php adding addtional p tag into html during loop

I am experiencing strange behavior with my php. It is adding in an emoty paragraph in my html but I cannot figure out why.

I am looping over a json object that looks like this

{
"1495147646442": {
"description": "Wonderful!",
"fileNames": [
"1.jpg",
"2.jpg"
]
}
}


My php looks like the following.

<?php
$json = file_get_contents('auction.json');
$json = json_decode($json);

foreach ($json as $obj)
{

echo "<div class='row'>";
echo "<p>" . $obj->description . "</p>";

for ($x = 0; $x < count($obj->fileNames); $x++)
{
echo "<img class='col-md-6' src=" . $obj->fileNames[$x] . ">";
}

echo "</div>";

}
?>


The resulting html looks like this:

<div class='row'>
<p>Wonderful!</p>
<img class='col-md-6' src="1.jpg">
<img class='col-md-6' src="2.jpg">
</div>


<div class='row'>
<p></p>
</div>


however, I expect just to get

<div class='row'>
<p>Wonderful!</p>
<img class='col-md-6' src="1.jpg">
<img class='col-md-6' src="2.jpg">
</div>

Answer Source
Just check $obj->description is not empty in your foreach loop.

<?php
  $json = file_get_contents('auction.json');
  $json = json_decode($json);

  foreach ($json as $obj)
    {
        if(isset($obj->description) && $obj->description != ''){

            echo "<div class='row'>";
            echo "<p>" . $obj->description . "</p>";

            for ($x = 0; $x < count($obj->fileNames); $x++)
            {      
            echo "<img class='col-md-6' src=" . $obj->fileNames[$x] . ">"; 
            }

            echo "</div>";
        }

  }
?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download