匹配具有不同值和不同顺序php的数组的值

时间:2017-11-07 11:31:03

标签: php arrays foreach

我有两个数组

$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
}
?>

输出应该是 enter image description here

提前致谢

2 个答案:

答案 0 :(得分:1)

这很简单,只需检查$array2in_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; ?>