【发布时间】:2021-06-01 20:39:51
【问题描述】:
我在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 statement in the middle of concatenation?
PHP if... else alternative syntax throwing "unexpected ':' in..." error message
How to concatenate if statement inside echo in php?
所有这些都说要使用三元运算符,我正在这样做,但是不清楚如何具体格式化它,上面的答案也没有明确说明如何利用 strtotime 函数并输出日期。
Concatenation of multiple ternary operator in PHP? unexpected ')'
这表明你需要一个 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 上显示错误
致命错误:未捕获错误:语法错误,意外';'
【问题讨论】:
-
可能是我,但我的猜测是您只是缺少 if 语句的“错误”部分,并且您在发布的尝试中弄乱了括号。像这样试试;
<h5>' . ($webinar ? date("F d, Y", strtotime($webinarDate)) : "" ) . '</h5>。注意左括号和右括号的数量,并与您尝试的进行比较。 -
啊,就是这样,我迷失在所有括号等的杂草中
-
三元if语句的结构如下:
condition ? valueWhenTrue : valueWhenFalse。三个操作数必须是表达式,并且每个表达式的括号必须平衡。
标签: php