【问题标题】:PHP (un)check a checkbox from 2 dynamic arrays while comparing themPHP(取消)在比较它们时从2个动态数组中选中一个复选框
【发布时间】:2023-03-23 05:26:02
【问题描述】:

我有 2 个数组,$item 和 $previousItem。 $item 包含所有可能的选择 $previousItem 包含已存储在数据库中的选择。例如,我有带有苹果、橙子、香蕉的复选框,在我的数据库中我记录了用户之前选择了苹果和香蕉。如何填写复选框,以便仅取消选中橙色,而选中其他两个。如果我对 $previousItem 有多个值,则嵌套的 for 循环会创建重复项。这必须仅使用 php 来完成。有没有我可以使用的排序功能?

代码如下:

    for($i = 0; $i < $index; $i++)
        for($j = 0; $j < $count; $j++)
    {
        echo '<li>
                <!--these are the individual check boxes-->';
        echo '<input type="checkbox" name="item[]" id="$item+$count" value="' . $item[$j] . '"'.($previousItem[$i] == $item[$j] ?'checked': '') .'>
                <!--these are the values of the check boxes-->
                <label for="$item+$count">' . $item[$j] . '</label>
                <input type="hidden" name="item_list[]" value="' . $item[$j] . '">';
    }

【问题讨论】:

    标签: php sql html checkbox


    【解决方案1】:

    $item 中的每个元素只需要一个复选框。因此只做一个循环,超过 $item。它给出了重复项,因为它为 $previousItem ($i 循环)中的 every 元素列出了 $item ($j 循环)中的元素。

    阅读PHP: in_array function. 如果你用它代替$previousItem[$i] == $item[$j],你可以消除$previousItem 循环。语法类似于in_array($item[$j],$previousItem)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-15
      • 2021-12-23
      • 2014-03-12
      • 2021-05-22
      • 2013-08-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多