Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

write php if statement inside html element I create with php

I use php to create html elements based on documents from a mongodb collection .

$cursor = $collection->find(array('category'=>$ProductType)); //gets my items 
//then for each item create an html element 
foreach($cursor as $doc){
   echo " 
         <div class= 'product'>
              <h2> ".doc["title"]." </h2> //add product name property as element 
              //here i want to check if my product has a price then display the price 
              //but i do not know how to use if statement here  
        </div>
      ";
}

    

The problem is that I do not know how to use an if statement inside an echo " ..."; where an html element is created .

This is what I am trying to do :

if(doc['price']!=0){
   echo <h2> ".doc["price"]." </h2>
 }      

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can start and stop the echo any time and then restart it

$cursor = $collection->find(array('category'=>$ProductType)); //gets my items 
//then for each item create an html element 
foreach($cursor as $doc){
   echo "<div class= "product">
            <h2>$doc[title]</h2>";
    if($doc['price']!=0){
        echo "<h2>$doc[price]</h2>";
    }
    echo "</div>";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...