首页 > 解决方案 > PHP - 字符串连接中的三元运算符与 strtotime - “语法错误 - 意外')'”

问题描述

我有一个自定义函数,functions.php它返回 HTMl 和一些数据。我需要通过条件传递其中的一些来检查它是否存在,否则不要打印它。

我所拥有的看起来像这样:

$webinarDate = get_field('webinar_date');

// more code between here

$filteredresourcesHtml .= '
            <div class="cell small-12 medium-4 large-3 equal-height">
                <a class="asset-block ' . $post_type . '" href="' . $resource_url . '">
                  <i class="icon-' . $post_type . '"></i>
                  <p class="content-type">' . ucfirst($post_type_display) . '</p>
                  <h4>' . $shortTitle . '</h4>
                  <h5>' . ($webinarDate ? date("F d, Y", strtotime($webinarDate))) . '</h5>
                </a>
            </div>';

重要的一行是这样的:

<h5>' . ($webinar ? date("F d, Y", strtotime($webinarDate))) . '</h5>

上面的行给了我:

致命错误:未捕获的错误:语法错误,意外')'

if 语句在连接中间?

PHP if... else 替代语法抛出“unexpected ':' in...”错误信息

如何在php中的echo中连接if语句?

所有这些都说要使用三元运算符,我正在这样做但是不清楚如何具体格式化它,并且上面的答案也没有提供关于如何利用strtotime函数和输出日期的清晰说明。

PHP中多个三元运算符的连接?出乎意料的')'

这表明你需要一个 else 所以我尝试了:

<h5>' . ($webinarDate ? (date("F d, Y", strtotime($webinarDate)) : ('')) . '</h5>

但这给了我

致命错误:未捕获错误:语法错误,意外':'

如何在 strtotime 的字符串连接中使用三元运算符?这个的语法具体是什么?

我目前最接近的是:

<h5>' . (($webinarDate) ? (date("F d, Y", strtotime($webinarDate))) . '</h5>

但在整个声明中:

$filteredresourcesHtml .= '
            <div class="cell small-12 medium-4 large-3 equal-height">
                <a class="asset-block ' . $post_type . '" href="' . $resource_url . '">
                  <i class="icon-' . $post_type . '"></i>
                  <p class="content-type">' . ucfirst($post_type_display) . '</p>
                  <h4>' . $shortTitle . '</h4>
                  <h5>' . (($webinarDate) ? (date("F d, Y", strtotime($webinarDate))) . '</h5>
                </a>
            </div>';

我在最后一个 div 上收到一个错误,上面写着

致命错误:未捕获错误:语法错误,意外';'

标签: php

解决方案


您好,最适合您的是在变量中获取三元条件的值,然后将其连接到您想要的字符串中

$filteredresourcesHtml = condition ? $firstValue: $defaulValue

推荐阅读