2017-01-01 79 views
1

這裏我有兩個數組1.響應2.selected_amenties,在第一個數組值我顯示在複選框中,現在我想進行檢查值游泳池和電源備份因此值等於第一個數組(響應),該怎麼辦?如何使複選框在兩個陣列中檢查

<?php 
$response = Array 
(
    Array 
     (
      "id" => "57e2340eaebce1023152759b", 
      "name" => "Squash Court", 
      "amenityType" => "Sports" 
     ), 
    Array 
     (
      "id" => "57e23470aebce1023152759d", 
      "name" => "Swimming Pool", 
      "amenityType" => "Sports" 
     ), 
    Array 
     (
      "id" => "57e2347caebce1023152759e", 
      "name" => "Power Backup", 
      "amenityType" => "Convenience" 
     ), 
    Array 
     (
      "id" => "57e23486aebce1023152759f", 
      "name" => "Day Care Center", 
      "amenityType" => "Convenience" 
     ) 
); 

$selected_amenties = Array("0" => "Swimming Pool", 
          "1" => "Power Backup" 
         ); 
foreach($response as $amenity) 
{ 
?> 
<div class="checkbox"> 
<input type="checkbox" class="aminit" name="aminit" value="<?php echo $amenity['name']?>"><?php echo $amenity['name']?> 
</div> 
<?php 
} 
?> 

回答

1

嘗試這樣的:

<?php 
foreach($response as $amenity) 
{ 
    $checked = in_array($amenity['name'], $selected_amenties) ? 'checked' : ''; 

    ?> 
    <div class="checkbox"> 
    <input type="checkbox" class="aminit" name="aminit" value="<?php echo $amenity['name'] ?>" <?php echo $checked; ?>><?php echo $amenity['name']?> 
    </div> 
<?php 
} 
?> 
+0

感謝馬里蘭州馬思富蘇爾·拉曼 –

+0

歡迎。 @SagunthalaK –

0
$selected_amenties = array('Swimming Pool', 'Power Backup'); 

foreach($response as $amenity) { 
    $check = ''; 
    in_array($amenity, $selected_amenties) and $check = ' checked="checked" '; 
    echo '<div class="checkbox">'; 
    echo '<input type="checkbox" ' . $check . ' class="aminit" name="aminit" value="<?php echo $amenity['name']?>"><?php echo $amenity['name']?>'; 
    echo '</div>'; 
} 
相關問題