我把这段代码和各种if和elseif if语句拼凑在一起,只是想知道它是否可以整理一下(我的语法知识是垃圾!):
而不是再次显示所有的html代码(因为它们是一样的),有没有一种方法可以把所有的elseif if和if合并成一个呢?
if(in_array("Branding", get_field('categories')) && $grid_title == "Branding"){
echo "
<div class=\"grid-box\" onclick=\"location.href='" . get_page_link($post->ID) ."';\" style=\"cursor: pointer;\">
<div class=\"phase-1\">
<img class=\"grid-image\" src=\"" . $fields->thumb_image . "\" alt=\"" . $fields->company_name ."\" height=\"152\" width=\"210\" />
<div class=\"grid-heading\">
<h2>". $fields->company_name ."</h2>
<h3>" . implode(', ',get_field('categories')) ."</h3>
</div>
</div>
<div class=\"phase-2\">
<div class=\"grid-info\">
<h4>". $fields->project_name ."</h4>
<p>". $fields->description ."</p>
</div>
<div class=\"grid-heading-hover\">
<h2>". $fields->company_name ."</h2>
<h3>". implode(', ',get_field('categories')) ."</h3>
</div>
</div>
</div>
";
}
elseif(in_array("Web", get_field('categories')) && $grid_title == "Web"){
echo "
<div class=\"grid-box\" onclick=\"location.href='" . get_page_link($post->ID) ."';\" style=\"cursor: pointer;\">
<div class=\"phase-1\">
<img class=\"grid-image\" src=\"" . $fields->thumb_image . "\" alt=\"" . $fields->company_name ."\" height=\"152\" width=\"210\" />
<div class=\"grid-heading\">
<h2>". $fields->company_name ."</h2>
<h3>" . implode(', ',get_field('categories')) ."</h3>
</div>
</div>
<div class=\"phase-2\">
<div class=\"grid-info\">
<h4>". $fields->project_name ."</h4>
<p>". $fields->description ."</p>
</div>
<div class=\"grid-heading-hover\">
<h2>". $fields->company_name ."</h2>
<h3>". implode(', ',get_field('categories')) ."</h3>
</div>
</div>
</div>
";
}
else {
echo "hello";
}发布于 2011-05-19 19:25:24
elseif if和第一个if做同样的事情。因此,使用OR将条件移动到第一个条件,并删除elseif:
if((in_array("Branding", get_field('categories')) && $grid_title == "Branding") || (in_array("Web", get_field('categories')) && $grid_title == "Web")){
echo "
<div class=\"grid-box\" onclick=\"location.href='" . get_page_link($post->ID) ."';\" style=\"cursor: pointer;\">
<div class=\"phase-1\">
<img class=\"grid-image\" src=\"" . $fields->thumb_image . "\" alt=\"" . $fields->company_name ."\" height=\"152\" width=\"210\" />
<div class=\"grid-heading\">
<h2>". $fields->company_name ."</h2>
<h3>" . implode(', ',get_field('categories')) ."</h3>
</div>
</div>
<div class=\"phase-2\">
<div class=\"grid-info\">
<h4>". $fields->project_name ."</h4>
<p>". $fields->description ."</p>
</div>
<div class=\"grid-heading-hover\">
<h2>". $fields->company_name ."</h2>
<h3>". implode(', ',get_field('categories')) ."</h3>
</div>
</div>
</div>
";
}
else {
echo "hello";
}发布于 2011-05-19 19:27:08
您应该考虑使用PHP的Heredoc来分隔字符串。这将有助于消除回声和所有转义字符\‘。
使用PHP的if/else/elseif/endif简写语法。它使它更容易阅读:
if(condition) :
//statments
elseif(condition) :
//statments
endif;发布于 2011-05-19 19:34:16
如果我是你,我会保持HTML为纯文本,而不是PHP字符串:
<?php if(condition) : ?>
// html
<?php elseif(condition) : ?>
// html
<?php endif; ?>这使得阅读IMO变得更加容易。
https://stackoverflow.com/questions/6057834
复制相似问题