2

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

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

2 回答 2

2

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

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


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

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

代码:(Demo)(没有解构的Demo

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>
于 2021-06-13T14:53:32.517 回答
0

我不理解你的代码,但你为什么不尝试在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>
于 2021-06-13T13:58:55.030 回答