我有两个数组
$array1 = array(
'categories',
'questions',
'difficulties'
);
和
$array2 = array(
[0] => 'categories_view',
[1] => 'categories_delete',
[2] => 'questions_view',
[3] => 'questions_edit',
[4] => 'difficulties_view',
)
我希望将上述数组的值与复选框选中的属性
匹配我尝试了下面的代码,但没有得到正确的输出。
<?php
foreach ($array1 as $key => $value) {
?>
<div class="col-sm-offset-2 col-sm-3">
<b><?php echo ucwords($value); ?></b>
</div>
<div class="col-sm-2">
<input type="checkbox" name="role[]" value="<?php echo $value;?>_view" <?php echo $array2[$key] == $value."_view". ? $checked : ''; ?> > View
</div>
<div class="col-sm-2">
<input type="checkbox" name="role[]" value="<?php echo $value;?>_edit" <?php echo $array2[$key] == $value."_edit". ? $checked : '' ; ?> > Edit
</div>
<div class="col-sm-2">
<input type="checkbox" name="role[]" value="<?php echo $value;?>_delete" <?php echo $array2[$key] == $value."_delete". ? $checked : ''; ?> > Delete
</div>
<?php
}
?>
提前致谢
答案 0 :(得分:1)
这很简单,只需检查$array2
中in_array
函数中是否显示所需的值:
<?php
foreach ($array1 as $key => $value) {
?>
<div class="col-sm-offset-2 col-sm-3">
<b><?php echo ucwords($value); ?></b>
</div>
<div class="col-sm-2">
<input type="checkbox" name="role[]" value="<?php echo $value;?>_view" <?php echo in_array($value . "_view", $array2) ? $checked : ''; ?> > View
</div>
<div class="col-sm-2">
<input type="checkbox" name="role[]" value="<?php echo $value;?>_edit" <?php echo in_array($value . "_edit", , $array2) ? $checked : '' ; ?> > Edit
</div>
<div class="col-sm-2">
<input type="checkbox" name="role[]" value="<?php echo $value;?>_delete" <?php echo in_array($value . "_delete", $array2) ? $checked : ''; ?> > Delete
</div>
<?php
}
?>
答案 1 :(得分:0)
<?php foreach ($array1 as $key => $value) :?>
<div class="col-sm-offset-2 col-sm-3">
<b><?php echo ucwords($value); ?></b>
</div>
<div class="col-sm-2">
<input type="checkbox" name="role[]" value="<?php echo $value;?>_view" <?php echo in_array($value . "_view", $array2) ? $checked : ''; ?> > View
</div>
<div class="col-sm-2">
<input type="checkbox" name="role[]" value="<?php echo $value;?>_edit" <?php echo in_array($value . "_edit", , $array2) ? $checked : '' ; ?> > Edit
</div>
<div class="col-sm-2">
<input type="checkbox" name="role[]" value="<?php echo $value;?>_delete" <?php echo in_array($value . "_delete", $array2) ? $checked : ''; ?> > Delete
</div>
<?php endforeach; ?>