【问题标题】:match values of arrays with different values and different order php匹配具有不同值和不同顺序php的数组的值
【发布时间】:2017-11-07 19:49:04
【问题描述】:

我有两个数组

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

输出应该是

提前致谢

【问题讨论】:

  • $checked 的价值是多少?

标签: php arrays foreach


【解决方案1】:

很简单,只需使用in_array 函数检查$array2 中是否存在所需值:

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

【讨论】:

  • 谢谢,我没想到,值也可以用来检查 in_array 函数。你节省了我很多时间。
【解决方案2】:
<?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; ?>

【讨论】:

    猜你喜欢
    • 2021-05-23
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    • 2019-02-18
    • 1970-01-01
    • 2016-06-22
    • 1970-01-01
    相关资源
    最近更新 更多