[英]PHP - ternary operator in string concatenation with strtotime - "syntax error - unexpected ')' "
我在functions.php
中有一个自定义 function。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>
上面的行给了我:
致命错误:未捕获的错误:语法错误,意外')'
PHP if... else 替代语法抛出“unexpected ':' in...”错误消息
所有这些都说要使用三元运算符,我正在这样做但是不清楚如何具体格式化它,并且上面的答案并没有清楚地说明如何利用strtotime
function 并输出日期。
这表明你需要一个 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 上收到一个错误,上面写着
致命错误:未捕获错误:语法错误,意外';'
您好,最适合您的是在变量中获取三元条件的值,然后将其连接到您想要的字符串中
$filteredresourcesHtml = condition ? $firstValue: $defaulValue
看起来您缺少“速记 if”语句的false
部分,并且您在尝试修复它时犯了一些错字。
<h5>' . ($webinarDate ? date("F d, Y", strtotime($webinarDate)) : "" ) . '</h5>
这应该有效。
“速记 if”的语法是;
Condition ? True : False
我之前的评论作为答案,以便可以将这个问题从未回答的列表中整齐地删除。 虽然它不是最丰富的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.