我可以缩短这段代码吗?

时间:2014-06-13 14:01:39

标签: php wordpress date

我有这个代码,我在PHP中非常糟糕,有人可以告诉我如何优化这个吗?我认为代码可能会更短?

我试图以某种方式把所有的回声放在一行但没有运气......

<?php
$metakey = 'evcal_srow';
$zeit = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = %s ORDER BY meta_value ASC", $metakey) );
 if ($zeit) {
 foreach ($zeit as $evcal_srow) {
 echo "<div class='datum'>";
 echo gmdate("d.m.Y", $evcal_srow);
 echo "</div>";
 echo "<div class='uhrzeit'>";
 echo gmdate("H:i", $evcal_srow);
 echo "</div>";
 }
 }
?>

THX!

3 个答案:

答案 0 :(得分:1)

您可以通过退出PHP来删除回声,但这是个人偏好。

<?php
$metakey = 'evcal_srow';
$zeit = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = %s ORDER BY meta_value ASC", $metakey) );
 if ($zeit) {
    foreach ($zeit as $evcal_srow) { ?>

       <div class='datum'> <?php echo gmdate("d.m.Y", $evcal_srow); ?> </div>
       <div class='uhrzeit'><?php echo gmdate("H:i", $evcal_srow); ?> </div>

     <? }
 }
?>

或者,您可以查看MVC以及如何加载单独的视图&#39;模板,负责显示您的信息。这样您就可以从视图中分离逻辑。

答案 1 :(得分:0)

您可以像这样链接echo语句。随着。你只需要添加另一个

<?php
$metakey = 'evcal_srow';
$zeit = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT meta_value FROM $wpdb->postmeta    WHERE meta_key = %s ORDER BY meta_value ASC", $metakey) );
if ($zeit) {
  foreach ($zeit as $evcal_srow) {
    echo "<div class='datum'>".gmdate("d.m.Y", $evcal_srow)."</div><div class='uhrzeit'>".gmdate("H:i", $evcal_srow);."</div>";
   }
}
?>

答案 2 :(得分:0)

您可以集中字符串,只调用一个echo,以及删除多余的空格。可读性较差,但行数较少。

<?php
$metakey = 'evcal_srow';
$zeit = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = %s ORDER BY meta_value ASC", $metakey) );
 if ($zeit) {
 foreach ($zeit as $evcal_srow) {
 echo "<div class='datum'>";
 echo gmdate("d.m.Y", $evcal_srow);
 echo "</div>";
 echo "<div class='uhrzeit'>";
 echo gmdate("H:i", $evcal_srow);
 echo "</div>";
 }
 }
?>

变为

<?php $metakey='evcal_srow'; $zeit=$wpdb->get_col($wpdb->prepare("SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = %s ORDER BY meta_value ASC", $metakey));
if($zeit){foreach($zeit as $evcal_srow){
    echo "<div class='datum'>".gmdate("d.m.Y", $evcal_srow)."</div><div class='uhrzeit'>".gmdate("H:i", $evcal_srow)."</div>";
}} ?>