簡體   English   中英

條件字符串和變量串聯

[英]conditioned string and variable concatenation

如何使用php在控制器中連接此語法。 方法1:

echo "<option '". if($p_main_cat_id==$value['main_cat_id']){echo 'selected';}."' value='".$value['main_cat_id']."'>".$value['name']."</option>";

//錯誤是:如果發生意外

方法2:

echo "<option '".<?php if($p_main_cat_id==$value['main_cat_id']){echo 'selected';} ?>."' value='".$value['main_cat_id']."'>".$value['name']."</option>";

錯誤是:

意外的“ <”

這些都給錯誤。請更正它。 謝謝!

您不能將字符串直接附加到if條件。 除非您使用三元運算符

您必須分成幾行。 喜歡:

選項1

echo "<option selected='";
if( $p_main_cat_id==$value['main_cat_id'] ) echo 'selected';
echo  "' value='" . $value['main_cat_id'] . "'>" . $value['name'] . "</option>";

選項2三元運算符

echo "<option selected='" . ( $p_main_cat_id == $value['main_cat_id'] ? 'selected' : '' ) . "' value='".$value['main_cat_id']."'>".$value['name']."</option>";

選項3

或者,您可以將值存儲在變量上並追加。

$isSelected = ""; //Init the variable with empty string. 
if( $p_main_cat_id == $value['main_cat_id'] ) $isSelected = 'selected'; //Use the condition here, if true, assign selected' to the variable

//You can now append the variable here
echo "<option selected='" . $isSelected . "' value='" . $value['main_cat_id'] . "'>" . $value['name'] . "</option>";

嘗試三元運算符:

echo "<option ". $p_main_cat_id==$value['main_cat_id'] ? "selected": ""." value='".$value['main_cat_id']."'>".$value['name']."</option>";

方法2:

$selected = $p_main_cat_id==$value['main_cat_id'] ? "selected": "";
echo "<option ". $selected." value='".$value['main_cat_id']."'>".$value['name']."</option>";

最易讀的方法是預先設置變量,然后將其插入雙引號字符串中:

extract($value);
$selected = $main_cat_id == $p_main_cat_id ? "selected" : "";
echo "<option $selected value='$main_cat_id'>$name</option>";

這是一種簡單的清潔方法:

$option = '<option value="' . $value['main_cat_id'] . '" ';

// This is called a ternary operator and it basicaly means :
// If $p_main_cat_id == $value['main_cat_id'] is true then return 'selected >'
// Else return '>'
$option .= ($p_main_cat_id == $value['main_cat_id']) ? 'selected >' : '>';

$option .= $value['name'] . '</option>';

echo $option;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM