【问题标题】:ternary operator in array数组中的三元运算符
【发布时间】:2021-10-31 16:51:08
【问题描述】:

我正在尝试在 PHP 中的字符串中使用三元运算符

"hard_copy"=>"<input type='checkbox' (($station->hard_copy==1)?'checked':'') name='station[]' id='hard-copy-$key' class='hard-copy' value='hardcopy-$station->id-1' >
<label for='hard-copy-$key' style='margin-left: 30%;'></label>",

但我可能有一些语法错误

【问题讨论】:

  • 你能把错误包括进来吗
  • 没有错误我试图根据条件检查复选框并且复选框未被选中
  • 您不能像这样在双引号字符串中解压缩语句,只能解压缩变量。您需要使用串联。 "foo " . ($a == 1 ? 'checked' : '') . " bar"
  • 如果您遇到错误,请始终在您的问题中包含该错误。
  • 你不需要展示你的整个班级。您的问题已经得到解答,无论是在 cmets 中还是作为真正的答案。

标签: php


【解决方案1】:

我会回答我理解的问题
正如@Magnus Eriksson 提到的“你不能像这样在双引号字符串中解压缩语句,只有变量。你需要使用连接。”
试试这个

"hard_copy"=>
"<input type='checkbox' ". (($station->hard_copy==1) ? 'checked' : '') . "name='station[]' id='hard-copy-$key' class='hard-copy' value='hardcopy-$station->id-1' >
<label for='hard-copy-'".$key." style='margin-left: 30%;'></label>",

【讨论】:

  • 很好,但请解释一下你做了什么改变,这样他就可以从你的回答中学习。
  • 您能解释一下为什么我们必须为此使用串联吗?
  • 正如@Magnus Eriksson 提到的“你不能解压缩这样的双引号字符串中的语句,只有变量。你需要使用连接。”
【解决方案2】:

使用连接试试这个:

"hard_copy"=> "<input type='checkbox' ". ($station->hard_copy==1 ? 'checked':'' )." name='station[]' id='hard-copy-".$key."' class='hard-copy' value='hardcopy-".$station->id."-1' ><label for='hard-copy-".$key."' style='margin-left: 30%;'></label>",

【讨论】:

  • 还需要在语句前后加上括号:" . ($station-&gt;hard_copy == 1 ? 'checked' : '') . "
猜你喜欢
  • 1970-01-01
  • 2021-05-12
  • 1970-01-01
  • 2012-04-02
  • 2021-10-06
  • 2023-01-02
  • 1970-01-01
  • 2021-08-01
  • 2018-09-10
相关资源
最近更新 更多