简体   繁体   English

创建数组无法正常工作

[英]Creating Array not working as I thought

I've got myself really confused over arrays and I hope someone might be able to help me some. 我对数组感到非常困惑,希望有人可以帮助我一些。

I'm trying to store users selections of various pictures in a mysql database ( up to 3 pictures to choose from at a time). 我试图将用户选择的各种图片存储在mysql数据库中(一次最多可以选择3张图片)。 The selections are in fact checkboxes below each picture and I want to store these selections as $pic_id's in an array. 这些选择实际上是每张图片下方的复选框,我想将这些选择存储为$ pic_id的数组。

The selections are getting stored in my database but it seems that they are not being assigned keys as I expected and I can't seem to use them. 这些选择已存储在我的数据库中,但是似乎没有按我期望的那样为它们分配键,而且我似乎无法使用它们。

I want to be able to use the picture id's to show the selections made. 我希望能够使用图片ID来显示所做的选择。

This is my result: [7] => 11,6 [8] => 9,8 这是我的结果:[7] => 11,6 [8] => 9,8

but I need to get at these variables individually. 但是我需要单独查看这些变量。 I would expect this: [7] => 11, [8] =>6, [8] => 9, [9] => 8 我希望这样:[7] => 11,[8] => 6,[8] => 9,[9] => 8

The form: 表格:

 <form action="insert.php" method="GET">
    <?php
    <input type=\"checkbox\" name=\"pic_id[]\" value=".$row['id'].">
    <input type="submit" name="submit" value="Add" />
    ?>

insert.php insert.php

$checkBox = implode(',', $_GET['pic_id']);
if (isset($_GET['submit'])) {
$sql="INSERT INTO pics (pic_id) VALUES ('" . $checkBox . "')"; 

Print Array 打印阵列

<?php
    $sql="SELECT * FROM pics";
    $query = mysqli_query($conn, $sql);
    $myArray = Array();
    while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
    $myArray[]=$row['pic_id'];  
    }
 print_r($myArray);
?>

See result above. 见上面的结果。

Just separate the values like you concatenated them when inserting in the database. 就像将它们插入数据库时​​将它们串联起来一样,只需将它们分开即可。 Then loop through the results and add them to your array. 然后遍历结果并将它们添加到您的数组中。

<?php
    $sql="SELECT * FROM pics";
    $query = mysqli_query($conn, $sql);
    $myArray = array();
    while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
        foreach(explode(',', $row['pic_id']) as $id) {
            $myArray[]= $id;  
        }
    }
 print_r($myArray);
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM