在html中写php,用到流程控制的替换语法
原则是用冒号:
替换掉{}
知识点
if (true) {
echo 'xxx';
} else {
echo 'xxxx';
}
// 替换语法
if (true) :
echo 'xxx';
else :
echo 'xxxx';
endif;
if (true) :
echo 'xxx';
elseif (true) :
echo 'xxxx';
elseif (true) :
echo 'xxxx';
endif;
switch (true) :
case 'xxx':
//....
break;
case 'xxx':
//....
break;
case 'xxx':
//....
break;
default:
//...
endswitch;
while (true) {
//...
}
while (true) :
//...
endwhile;
for (;;) {
//....
}
for (;;) :
//....
endfor;
foreach ($data as $k=>$v) {
}
foreach ($data as $k=>$v) :
endforeach;
新闻列表
<?php
// 导入外部数据
$news = require 'data/news.php';
?>
<div class="news">
<h3>新闻列表</h3>
<div class="list">
<?php foreach ($news as $new) :
if($new['id'] <= 5) :
?>
<a href="<?=$new['url'] ?>"><?=$new['title'] ?></a>
<?php endif; endforeach ?>
</div>
</div>
产品列表
<?php
// 当然,也可以在循环体直接写for(i=1;i<=8;i++);不用在这里定义了
$products = [1,2,3,4,5,6,7,8];
?>
<div class="items">
<h3>产品列表</h3>
<div class="list">
<?php foreach ($products as $product) : ?>
<div class="item">
<img src="static/images/item<?=$product ?>.jpeg" alt="" />
<a href="">最新产品<?=$product ?></a>
</div>
<?php endforeach ?>
</div>
</div>