programing

echo 문 안에 블록이 있습니까?

shortcode 2021. 1. 16. 20:23
반응형

echo 문 안에 블록이 있습니까?


"구문 오류 : 구문 오류, 예상치 못한 T_IF in ..."오류가 발생하기 때문에 허용되지 않는 것 같습니다. 하지만 내 목표를 달성 할 방법을 찾지 못했습니다. 내 코드는 다음과 같습니다.

<?php 

  $countries = $myaddress->get_countries();

  foreach($countries as $value){
    echo '<option value="'.$value.'"'.if($value=='United States') echo 'selected="selected"';.'>'.$value.'</option>';
  }
  ?>

선택 요소에 국가 목록을 표시하고 미국을 기본값으로 설정합니다. 나는 슬프게 일하지 않는다 ...


사용하고 싶을 것입니다 그만큼단축 된 IF / Else 문 역할을 하는 삼항 연산자 :

echo '<option value="'.$value.'" '.(($value=='United States')?'selected="selected"':"").'>'.$value.'</option>';

당신은 항상 사용할 수 있습니다 ( <condition> ? <value if true> : <value if false> )(이것은라고 구문을 삼항 연산자 - 감사를 표시하려면 : 나를 remining 위해 ).

경우 <condition>사실, 문은 다음과 같이 평가 될 것이다 <value if true>. 그렇지 않은 경우 다음과 같이 평가됩니다.<value if false>

예를 들면 :

$fourteen = 14;
$twelve = 12;
echo "Fourteen is ".($fourteen > $twelve ? "more than" : "not more than")." twelve";

이것은 다음과 같습니다.

$fourteen = 14;
$twelve = 12;
if($fourteen > 12) {
  echo "Fourteen is more than twelve";
}else{
  echo "Fourteen is not more than twelve";
}

용도 삼항 연산자를 :

echo '<option value="'.$value.'"'.($value=='United States' ? 'selected="selected"' : '').'>'.$value.'</option>';

그리고 그 동안 printf코드를 더 읽기 쉽고 관리하기 쉽게 만드는 데 사용할 수 있습니다 .

printf('<option value="%s" %s>%s</option>',
    $value,
    $value == 'United States' ? 'selected="selected"' : ''
    $value);

가독성을 위해 다음과 같아야합니다.

<?php 
  $countries = $myaddress->get_countries();
  foreach($countries as $value) {
    $selected ='';
    if($value=='United States') $selected ='selected="selected"'; 
    echo '<option value="'.$value.'"'.$selected.'>'.$value.'</option>';
  }
?>

모든 것을 한 줄로 채우려는 욕망은 죽음입니다. 명확하게 작성하십시오.

하지만 더 나은 방법이 있습니다. 에코를 전혀 사용할 필요가 없습니다. 템플릿 사용 방법을 배웁니다 . 먼저 데이터를 준비하고 준비된 후에 만 ​​표시하십시오.

비즈니스 로직 부분 :

$countries = $myaddress->get_countries();
$selected_country = 1;    

템플릿 부분 :

<? foreach($countries as $row): ?>
<option value="<?=$row['id']?>"<? if ($row['id']==$current_country):> "selected"><? endif ?>
  <?=$row['name']?>
</option>
<? endforeach ?>

참조 URL : https://stackoverflow.com/questions/3507042/if-block-inside-echo-statement

반응형