1

我目前有这两个正在提取结果的 php 块:

<?php
    $webtech = article_custom_field('web-tech');
    if ( !empty($webtech) ) :
?>
    <div class="tech-list">
        <div class="tech-title">Technologies:</div>
        <ul class="tech-ul"><?php echo $webtech; ?></ul>
    </div>
<?php
    endif;
?>

<?php
    $url = article_custom_field('site-url');
    elseif ( !empty($url) ) :
?>
    <div class="site-url"><a href="<?php echo $url; ?>" target="_blank">Visit</a></div>
<?php
    endif;
?>

我想将它们组合起来输出一个块,例如:

<div class="tech-list">
    <div class="tech-title">Technologies:</div>
    <ul class="tech-ul"><?php echo $webtech; ?></ul>
    <div class="site-url"><a href="<?php echo $url; ?>" target="_blank">Visit</a></div>
</div>

它需要满足以下条件:

如果存在 web-tech,输出它。如果 site-url 不存在,则不要输出它。

如果存在 web-tech,输出它。如果 site-url 存在,则输出它。

如果 site-url 存在,则输出它。如果不存在,请不要输出 web-tech。

如果两个变量都不存在,则根本不应该输出包含的 div。

我错过了一个明显的方法吗?这似乎微不足道,但我无法让 if/else/elseif 语句对齐。

4

3 回答 3

2

听起来您需要在输出它们所在的容器之前检查这两个变量。

<?php
    $webtech = article_custom_field('web-tech');
    $url = article_custom_field('site-url');

    if ( !empty($webtech) || !empty($url))
    {
?>
    <div class="tech-list">
<?php
       if ( !empty($webtech) )
       {
?>
        <div class="tech-title">Technologies:</div>
        <ul class="tech-ul"><?php echo $webtech; ?></ul>
<?php
       }

       if ( !empty($url) )
       {
?>
        <div class="site-url"><a href="<?php echo $url; ?>" target="_blank">Visit</a></div>
<?php

       }
?>
    </div>
<?php
    }
?>
于 2013-10-18T15:41:45.960 回答
2

您可以将输出存储在变量中,如下所示:

<?php
    $output = '';
    $webtech = article_custom_field('web-tech');
    if ( !empty($webtech) ) :
        $output .= '<div class="tech-title">Technologies:</div>'
            . '<ul class="tech-ul">' . $webtech . '</ul>';
    endif;

    $url = article_custom_field('site-url');
    if(!empty($url)) :
        $output .= '<div class="site-url"><a href="' . $url . '" target="_blank">Visit</a></div>';
    endif;

    if($output != ''):
        echo '<div class="tech-list">';
        echo $output;
        echo '</div>';
    endif;
?>

这样,只有在您的输出变量中设置了某些内容时,它才会显示任何内容。

这能解决你的问题吗?

于 2013-10-18T15:42:22.927 回答
0
if (a or b) then {
  OpenTechTitle;
  if (a) SetAtext;
  if (b) SetBtext;
  CloseTechTitle;
}
于 2013-10-18T15:20:08.507 回答