微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 php 中使用 in_array 时缺少一个值

如何解决在 php 中使用 in_array 时缺少一个值

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

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

解决方法

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

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


我建议创建一个干净的模板字符串,以便在迭代时使用。 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>
,

我不明白你的代码,但是你为什么不尝试在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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。