2014-10-22 1 views
0

foreach 루프 내에서 만약 그렇지 사용올바르게 내가 foreach 루프 내에서 몇 가지 정보 인쇄하려고

<?php foreach($output['data']['rooms'] as $info): ?> 
      <?php if($info['room_number'] == $id): ?> 
       <h1 style="font-size: 20pt; color: white;">Room: <?php echo $info['room_number']; ?></h1> 
       <?php echo '<a style="float: right;" class="button1" href="'.$curIndex.'">Home</a>'; ?> 
       <hr style="margin-top: 20px;"> 
        <?php $services = reset($info['services']); ?> 
       <h2 style="font-size: 14pt; color: #924c9e;"> Room Charges: <?php echo ($services['room_charges']['enabled'] == 1) ? 'ENABLED' : 'DISABLED'; ?></h2> 
       <h2 style="font-size: 14pt; color: #924c9e;"> Adult: <?php echo ($services['adult']['enabled'] == 1) ? 'ENABLED' : 'DISABLED'; ?> </h2>    
       <h2 style="font-size: 14pt; color: #924c9e;"> Room Status: <?php echo $info['status']; ?></h2> 
    <?php else : echo "No data found for the room number you entered."; ?> 
     <?php endif; ?> 
     <?php endforeach; ?> 

제대로 작동하지 않는 부분은 <?php else: "no data found for the room number you entered."; ?>

else 문은 에코의입니다 정보에 대한 foreach 루프 내에있는 모든 엔트리가 단 한 번이 아니라 반복됩니다. 내가 뭘하려고하는지 설명하는 가장 쉬운 방법 : id과 일치하는 경우

id 사용자가 입력 한 다음 해당 방 번호에 해당하는 모든 것을 인쇄하고 그 방의 데이터를 찾을 수 없습니다. 방 번호를 찾을 수없는 경우에만 "No data found for the room number you entered" 페이지에 한 번만 표시하면됩니다.

필요한 경우 더 많은 코드를 제공 할 수 있지만이 코드를 사용해야한다고 생각합니다. 방금 foreach 루프 내에 else을 정확하게 포함 할 수 없었습니다.

도움 주셔서 감사합니다. 제가 알아낼 수 있도록 도와 주시면 정확한 답을 표시하겠습니다.

+0

호텔 정보가 올바르게 인쇄됩니까? 아니면 그냥 else 문에 텍스트를 인쇄합니까? – Gohn67

+0

호텔 정보를 올바르게 인쇄합니다. 방 번호 == id, 방 번호에 대한 정보를 인쇄합니다. 방 번호! == id 인 경우 foreach 루프 내의 각 항목에 대해 수십 개의 "데이터가 없음"으로 표시됩니다. @ Gohn67 – ValleyDigital

+0

이 예에서는 12 개의 객실이 있으며 12 개의 모든 객실에 대해 "데이터 없음 ..."을 인쇄하지만 올바른 호텔 정보도 인쇄됩니까? 죄송합니다, 제가 이해하고 있는지 확인하고 싶습니다. – Gohn67

답변

1

일반적으로이 작업을 수행하는 방법은 사용자의 작업과 약간 다릅니다.

// TODO: declare a variable called matchFound and set to false 
foreach($output['data']['rooms'] as $info): 
    if($info['room_number'] == $id): 
     // TODO: set matchFound = true 
     // TODO: print out room data 
     // TODO: break the foreach loop since looping through the remaining records is pointless 
    endif; 
endforeach; 
// TODO: if the matchFound variable is false, then print the "No data found for the room number you entered" message 

설명이 필요한 경우 알려 주시기 바랍니다. PHP를 사용한 이래로 얼마간의 시간이 걸렸으므로 구문에 약간 녹슬었지만 직접 생각할 수 없다면 "TODO :"행을 작성하는 방법을 알아낼 수있었습니다.

편집, 나는 이것이 올바른 구문 생각하고 그것을 작동합니다 :

<?php $matchFound = false; ?> 
<?php foreach($output['data']['rooms'] as $info): ?> 
    <?php if($info['room_number'] == $id): ?> 
     <?php $matchFound = true; ?> 
     <h1 style="font-size: 20pt; color: white;">Room: <?php echo $info['room_number']; ?></h1> 
     <?php echo '<a style="float: right;" class="button1" href="'.$curIndex.'">Home</a>'; ?> 
     <hr style="margin-top: 20px;"> 
     <?php $services = reset($info['services']); ?> 
     <h2 style="font-size: 14pt; color: #924c9e;"> Room Charges: <?php echo ($services['room_charges']['enabled'] == 1) ? 'ENABLED' : 'DISABLED'; ?></h2> 
     <h2 style="font-size: 14pt; color: #924c9e;"> Adult: <?php echo ($services['adult']['enabled'] == 1) ? 'ENABLED' : 'DISABLED'; ?> </h2>    
     <h2 style="font-size: 14pt; color: #924c9e;"> Room Status: <?php echo $info['status']; ?></h2> 
     <?php break; ?> 
    <?php endif; ?> 
<?php endforeach; ?> 
<?php if (!$matchFound): ?> 
    <?php echo "No data found for the room number you entered."; ?> 
<?php endif; ?> 
+1

나는 그 방법으로 그것을 시도했다. 문제는 여전히 room_number == id이고 올바른 정보를 가져 왔고 그 아래 matchFound 변수는 여전히 "데이터 없음"을 인쇄했습니다 ... 만약 당신이 ' 그 얘기는 대단 할 것입니다. 그러나 너무 많이 걱정하지 마라, 나는 아직도 그것에 대해 연구 중이다. 그래도 감사합니다! – ValleyDigital

+1

완벽합니다. 고맙습니다! 방금 마지막 ValleyDigital

+1

당신은이 질문에 큰 도움이되었습니다. 나는 당신이 내가 가지고있는이 새로운 질문을 살펴보기 바란다면 궁금 해서요 http://stackoverflow.com/questions/26744290/json-creating-a-form-to-search-a-date-range-using-datetime- 가치 – ValleyDigital

1

내가 제대로 상황을 이해한다면, 당신은 당신이 방을 찾을 수없는 것을 확인 한 번 반복 중지하고 싶습니다.

그렇다면 (else 조건에서 break 문을 추가했습니다.) 그렇다면이 작업을 수행하십시오. else 조건이 {}로 충족 될 때 수행 할 작업을 캡슐화해야 할 수도 있습니다. 나는 if (condition) {우선 이것을한다; 이 두 번째;} 문법.

어떤 경우이든, else 조건에 도달 할 때 실행할 코드의 일부로 break 문을 추가하면 문제가 해결됩니다.

<?php foreach($output['data']['rooms'] as $info): ?> 
     <?php if($info['room_number'] == $id): ?> 
      <h1 style="font-size: 20pt; color: white;">Room: <?php echo $info['room_number']; ?></h1> 
      <?php echo '<a style="float: right;" class="button1" href="'.$curIndex.'">Home</a>'; ?> 
      <hr style="margin-top: 20px;"> 
       <?php $services = reset($info['services']); ?> 
      <h2 style="font-size: 14pt; color: #924c9e;"> Room Charges: <?php echo ($services['room_charges']['enabled'] == 1) ? 'ENABLED' : 'DISABLED'; ?></h2> 
      <h2 style="font-size: 14pt; color: #924c9e;"> Adult: <?php echo ($services['adult']['enabled'] == 1) ? 'ENABLED' : 'DISABLED'; ?> </h2>    
      <h2 style="font-size: 14pt; color: #924c9e;"> Room Status: <?php echo $info['status']; ?></h2> 
<?php else : echo "No data found for the room number you entered."; break;?> 
    <?php endif; ?> 
    <?php endforeach; ?> 
+0

이것이 문제를 해결할 수 있지만 문제를 해결하는 가장 좋은 방법은 아닙니다. 더 나은 솔루션이 있습니다. 그러나 기존 코드를 기반으로 대답을 제공했습니다. 여기를 참조하십시오 : [http://stackoverflow.com/questions/9215588/break-out-of-if-and-foreach] – arkyc

+0

이것은 foreach 루프에 반복되는 항목 문제를 해결했습니다. 고맙습니다. 문제는 방 번호 == id 인 경우에도 else 문이 여전히 적용된다는 것입니다. 올바른 정보를 표시하고 "no data found ..."라고 표시합니다. – ValleyDigital

+0

여전히 문제가 발생했는지는 모르겠지만 문자열을 비교할 것입니다. – arkyc

관련 문제