【问题标题】:Missing one value while using in_array in php在 php 中使用 in_array 时缺少一个值
【发布时间】:2021-08-29 12:30:22
【问题描述】:

我有两个数组,下面是输出。第一个数组是我的所有列表,第二个是由用户选择的。

$specification=getgeneralSpecifications($pdo); // getting below array

Array(
    [0] => Array
        (
            [sp_id] => 1
            [specifications_name] => example 1
        )

    [1] => Array
        (
            [sp_id] => 2
            [specifications_name] => example 2
        )

    [2] => Array
        (
            [sp_id] => 3
            [specifications_name] => example 3
        )

    [3] => Array
        (
            [sp_id] => 4
            [specifications_name] => example 4
        )

    [4] => Array
        (
            [sp_id] => 5
            [specifications_name] => example 5
        )

    [5] => Array
        (
            [sp_id] => 6
            [specifications_name] => example 6
        )

)
    $getgeneral = explode(",",$info['developerprofile']['general_Specifications']); // getting below output

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

我必须显示数据库中的所有列表,并且我已经根据获取表单数据库的第二个数组值选中了复选框。

我尝试了以下代码,我得到了输出但缺少一个值。 我的意思是,如果我有数组 1,2,3,4,那么我将继续使用 1,2,3

    <?php 
    $specification=getgeneralSpecifications($pdo);
    $getgeneral = explode(",",$info['developerprofile']['general_Specifications']);

    foreach ($specification as $key=> $row) {
      $checked="";
      if(in_array($key, $getgeneral)){
        $checked="checked";
          }
      ?>
      <li><label><?php echo $row['specifications_name'];?></label>
        <div class="form-check">
          <input class="form-check-input custom-checkbox generalsinglecheck" type="checkbox" value="<?php echo $row['sp_id'];?>" name="general_specification[]" <?php echo $checked;?>>
        </div>
      </li>
    <?php } ?>

【问题讨论】:

  • in_array() 是你的朋友。见the manual
  • @Michel,那么我需要使用 foreach 吗?
  • if ( in_array ( $row['sp_id'], $your_user_array ) )
  • @mickmackusa,实际上我必须显示所有列表,选择的 .getgeneralSpecifications() 显示所有列表,$getgeneral 显示选择的。
  • @mickmackusa,是的,你是对的,在我尝试相同之前,但现在一些场景更改为现在我必须在用户可以更新更多列表的编辑页面上显示所有列表。跨度>

标签: php html checkbox foreach nested-for-loop


【解决方案1】:

这是一个错误的行索引和sp_id 值(也是数字)的简单问题。

您的$key 变量更适合命名为$index,但事实是您根本不需要声明该变量。相反,在与$getgeneral 数组进行比较时,请参考该行的sp_id,一切都会好起来的。


我建议创建一个干净的模板字符串,以便在迭代时使用。 printf() 非常适合这种技术。通过这种方式,您可以整齐地标记您的标记,而无需使用与内联条件块混合的凌乱插值/连接。

哦,我将在 foreach() 中演示数组解构,但您不一定需要这样做 - 如果您愿意,可以通过键访问子数组值。

代码:(Demo) (Demo without destructuring)

function getgeneralSpecifications() {
    return [
        ['sp_id' => 1, 'specifications_name' => 'example 1'],
        ['sp_id' => 2, 'specifications_name' => 'example 2'],
        ['sp_id' => 3, 'specifications_name' => 'example 3'],
        ['sp_id' => 4, 'specifications_name' => 'example 4'],
        ['sp_id' => 5, 'specifications_name' => 'example 5'],
        ['sp_id' => 6, 'specifications_name' => 'example 6'],
    ];
}

$checked = explode(',', '1,2,4');

echo "<ul>";
foreach (getgeneralSpecifications() as ['sp_id' => $id, 'specifications_name' => $name]) {
    printf(
        '<li>
            <label>%s</label>
            <div class="form-check">
                <input class="form-check-input custom-checkbox generalsinglecheck"
                       type="checkbox"
                       value="%d"
                       name="general_specification[]"
                       %s>
            </div>
        </li>',
        $name,
        $id,
        in_array($id, $checked) ? 'checked' : ''
    );
}
echo "</ul>";

输出:

<ul>
    <li>
        <label>example 1</label>
        <div class="form-check">
            <input class="form-check-input custom-checkbox generalsinglecheck"
                   type="checkbox"
                   value="1"
                   name="general_specification[]"
                   checked>
        </div>
    </li>
    <li>
        <label>example 2</label>
        <div class="form-check">
            <input class="form-check-input custom-checkbox generalsinglecheck"
                   type="checkbox"
                   value="2"
                   name="general_specification[]"
                   checked>
        </div>
    </li>
    <li>
        <label>example 3</label>
        <div class="form-check">
            <input class="form-check-input custom-checkbox generalsinglecheck"
                   type="checkbox"
                   value="3"
                   name="general_specification[]"
                   >
        </div>
    </li>
    <li>
        <label>example 4</label>
        <div class="form-check">
            <input class="form-check-input custom-checkbox generalsinglecheck"
                   type="checkbox"
                   value="4"
                   name="general_specification[]"
                   checked>
        </div>
    </li>
    <li>
        <label>example 5</label>
        <div class="form-check">
            <input class="form-check-input custom-checkbox generalsinglecheck"
                   type="checkbox"
                   value="5"
                   name="general_specification[]"
                   >
        </div>
    </li>
    <li>
        <label>example 6</label>
        <div class="form-check">
            <input class="form-check-input custom-checkbox generalsinglecheck"
                   type="checkbox"
                   value="6"
                   name="general_specification[]"
                   >
        </div>
    </li>
</ul>

【讨论】:

  • 说实话,我没有看懂最后的$name, $id。直到现在我还没有使用过这种foreach。
  • 如果您能帮助我编写代码,我会更高兴。我需要明白我错在哪里。我会参考您的答案以供将来参考。
  • 哦!是的,现在我明白你的意思了。我必须像这样使用 if(in_array($row['sp_id'], $getgeneral)) 它解决了我的问题。
  • 请同时更新此答案。我会接受的。
  • 你应该得到我的支持。实际上,我所在的位置存在一些互联网问题。
【解决方案2】:

我不理解你的代码,但是为什么你不尝试在 java 脚本中使用你的复选框作为数组,通过尝试类似的东西,

例子:

<?php
//you-php-response.php
require "database.php";
$db = new DataBase();
if (isset($_POST['sp_id']) ) {
    if ($db->dbConnect()) {
        if ($db->setlist("my_list_2", $_POST['sp_id'])) {
            echo "Add to list";

        } else echo "something went wrong";
    } else echo "Error: Database connection";
} else echo "All fields are required";

还有你的 database.php :

<?php
require "DataBaseConfig.php";

class DataBase
{
    public $connect;
    private $stm;
    protected $servername;
    protected $username;
    protected $password;
    protected $databasename;

    public function __construct()
    {
        $this->connect = null;
        $this->stm = null;
        $dbc = new DataBaseConfig();
        $this->servername = $dbc->servername;
        $this->username = $dbc->username;
        $this->password = $dbc->password;
        $this->databasename = $dbc->databasename;
    }

    function dbConnect()
    {
        $this->connect = new PDO('mysql:host='.$this->servername.';dbname='.$this->databasename.'', $this->username, $this->password);
        return $this->connect;
    }

    function setlist($table, $sp_id)
    {
         $this->stmq = "INSERT INTO ".$table."( `sp_id_token`) VALUES ('?')";
         $this->stm = $this->connect->prepare($this->stmq) ;
          if ($this->stm->bind_param("ssis", $this->my_sup_id)) {
              $this->my_sup_id = "$sp_id";
              $this->stm->execute();
             return true;
           } else return false;  
    }

    function getmycheckboxRander()
    {
         $this->stmq = "SELECT* FROM `my_list_1` ";
         $this->stm = $this->connect->prepare($this->stmq);
         $this->stm->execute();
         $this->result =   $this->stm->fetchAll();
         $this->body = array();
         foreach($this->result as $this->row){
              $this->sp_id= $this->row['sp_id'];
              $this->my_sup_name = $this->row['sup_name'];
              $this->body[] = array("<div class='card ew-card card-body'><p><input 
             type='checkbox' name='type' value=".$this->sp_id." />".$this->my_sup_name." </p></div>");
        }
     return $this->body;
    }
}

和'DataBaseConfig.php'

<?php

class DataBaseConfig
{
    public $servername;
    public $username;
    public $password;
    public $databasename;

    public function __construct()
    {

        $this->servername = 'localhost';
        $this->username = 'root';
        $this->password = 'pass@';
        $this->databasename = 'data_base';

    }
}

?>

你的脚本应该是这样的

<?php
require_once "database.php";
$db = new DataBase();
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
<?php if($db->dbConnect()){?>
    var mylist= <?= json_encode($db->getmycheckboxRander())?>;
<?php }?>
    document.getElementById("mylistarray").innerHTML = mylist;
        $('button').on('click', function() {
            var array = [];
            $("input:checkbox[name=type]:checked").each(function() {
                var sup_id = $(this).val();
                jQuery.ajax({
                   url:'your-php-response.php',
                    type:'post',
                    data:'sp_id ='+sup_id ,
                        success:function(result){
                          window.location.href=window.location.href 
                     }
                 });
            });          
        });
</script>
//then the result
<div id="mylistarray"></div>
  <button class="btn btn-success" >Add to list</button>

【讨论】:

  • mysqli 查询不安全/不稳定,任何人都不应使用。 mysqli_connect_error() 永远不应呈现给最终用户。与面向对象的语法相比,过程式 mysqli 语法更冗长/吸引力更小。
  • @Adan,我尝试了另一种解决方案,它几乎可以工作,但我缺少一个。我更新了问题中的代码。
  • 请理解,当您在 Stack Overflow 上发布答案时,您绝不只是在与 OP 交谈——您正在与成千上万的未来研究人员交谈。永远不要推荐您知道不安全或不会在您自己的专业应用程序中编写的代码。您的答案每次都必须展示您的知识。
  • 我不认为你很粗鲁。我不推荐mysqli_real_escape_string()——它不再是现代标准。只应使用准备好的语句。除此之外,有证据表明 OP 使用的是 PDO 而不是 MySQLi。
  • 我不是最好的。我只是一个正在努力学习好php的初级开发人员。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-30
  • 2011-07-01
  • 1970-01-01
  • 2019-06-21
  • 1970-01-01
  • 2014-07-26
  • 1970-01-01
相关资源
最近更新 更多