You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP的echo语句中添加if/else条件实现内容展示?

在PHP的echo中整合if/else条件展示内容的解决方案

问题描述

需要在echo输出的内容中整合if/else条件,根据文章所属的countries分类项展示对应国旗,现有两段尝试代码存在逻辑或语法问题,需修正。

现有尝试代码1

<?php if ( is_object_in_term( $loop->post->ID, 'countries', 'germany' ) ) {
          echo '<div class="speaker-flag"><img src="/wp-content/uploads/2022/08/flag-for-germany.svg"></div>';
      } else if ( is_object_in_term( $loop->post->ID, 'countries', 'switzerland' ) ) {
          echo '<div class="speaker-flag"><img src="/wp-content/uploads/2022/08/flag-for-switzerland.svg"></div>';
      } ?>

echo '<li></li>'

现有尝试代码2

$germany_flag = "/wp-content/uploads/2022/08/flag-for-germany.svg";
$swiss_flag = "/wp-content/uploads/2022/08/flag-for-switzerland.svg";
$is_germany = is_object_in_term( $loop->post->ID, 'countries', 'germany' );

'<li>
      <div class="speaker-flag"><img src="'.$is_germany ? $germany_flag : $swiss_flag .'"></div>
</li>'

解决方案

方案1:整合多分支条件到统一输出

第一段代码的问题是条件判断与li标签的输出分离,导致结构零散。可以先将条件判断结果存入变量,再统一输出完整的li结构:

<?php
// 初始化国旗HTML为空
$flag_html = '';

// 根据文章所属分类确定国旗内容
if (is_object_in_term($loop->post->ID, 'countries', 'germany')) {
    $flag_html = '<div class="speaker-flag"><img src="/wp-content/uploads/2022/08/flag-for-germany.svg"></div>';
} elseif (is_object_in_term($loop->post->ID, 'countries', 'switzerland')) {
    $flag_html = '<div class="speaker-flag"><img src="/wp-content/uploads/2022/08/flag-for-switzerland.svg"></div>';
}

// 统一输出包含国旗的li标签
echo '<li>' . $flag_html . '</li>';
?>

方案2:修复三元运算符优先级问题

第二段代码的核心错误是字符串连接符.的优先级高于三元运算符?:,导致逻辑执行顺序错误。只需给三元运算部分添加括号即可修正:

<?php
$germany_flag = "/wp-content/uploads/2022/08/flag-for-germany.svg";
$swiss_flag = "/wp-content/uploads/2022/08/flag-for-switzerland.svg";
$is_germany = is_object_in_term($loop->post->ID, 'countries', 'germany');

// 给三元运算加括号,确保先执行条件判断再拼接字符串
echo '<li>
      <div class="speaker-flag"><img src="' . ($is_germany ? $germany_flag : $swiss_flag) . '"></div>
</li>';
?>

扩展方案:多国家场景的优雅处理

如果后续需要支持更多国家,建议使用数组映射替代大量elseif,提升代码扩展性:

<?php
// 定义国家与国旗URL的映射关系
$country_flag_map = [
    'germany' => '/wp-content/uploads/2022/08/flag-for-germany.svg',
    'switzerland' => '/wp-content/uploads/2022/08/flag-for-switzerland.svg',
    // 新增国家时直接添加键值对即可
];

$flag_html = '';
// 遍历映射数组,匹配文章所属分类
foreach ($country_flag_map as $country_slug => $flag_url) {
    if (is_object_in_term($loop->post->ID, 'countries', $country_slug)) {
        $flag_html = '<div class="speaker-flag"><img src="' . $flag_url . '"></div>';
        break; // 找到匹配项后终止遍历
    }
}

echo '<li>' . $flag_html . '</li>';
?>

内容的提问来源于stack exchange,提问作者userName

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 03:15:35