首页 > 解决方案 > 在我用 php 创建的 html 元素中编写 php if 语句

问题描述

我使用 php 根据来自 mongodb 集合的文档创建 html 元素。

$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>
      ";
}

    

问题是我不知道如何在echo " ...";创建 html 元素的地方使用 if 语句。

这就是我想要做的:

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

标签: phphtml

解决方案


您可以随时启动和停止回声,然后重新启动它

$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>";
}

推荐阅读