MySql - 将数组值(匹配和不匹配)插入数据库匹配列

标签 mysql arrays for-loop foreach pdo

所以我有一个可选服装项目列表作为复选框,数量可能比下面的 5 个更多。

shoes, pants, skirt, socks, jacket //list of possible choices

在所选项目的 jquery 中创建一个逗号分隔的数组。假设选择了以下内容:

shoes, socks, jacket //array posted as $_POST['clothes']

在数据库中,每个客户在服装表中都有这些选项,在服装项目下有"is"或“否”。然而,服装项目的命名略有不同,但映射到相同的选项:

'clothes' table before insert
customer_id  dress_shoes  elegant_pants  long_skirt  ankle_socks  biker_jacket
     1            no            yes           no           no           no

使用 $_POST['clothes'],我尝试循环遍历数组,将数据库中的相应字段更新为“yes”,将非相应字段更新为“no”。我很难做到这一点。

'clothes' table after insert
customer_id  dress_shoes  elegant_pants  long_skirt  ankle_socks  biker_jacket
     1            yes            no           no          yes          yes

我做了一个 array_intersect 来将项目标记为"is":

$clothesArray = array("shoes", "socks", "jacket"); // Posted clothes
$clothesArrayAll = array("shoes", "pants", "skirt", "socks", "jacket"); // All clothes
$common = array_intersect($clothesArrayAll,$clothesArray);
print_r($common);
Array ( [0] => shoes [3] => socks [4] => jacket )

我试图以某种方式循环遍历 $clothesArrayAll,对普通衣服给出"is",对数组中的所有其他衣服给出“否”。然后,我尝试通过 PDO 更新“衣服”表,以最有效的方式将每个相应字段设置为"is"或“否”。在获得上面的常见衣服阵列后,我陷入困境,不知道如何继续。

有人可以帮我吗?

谢谢!

最佳答案

我认为你走在正确的道路上。我只需添加一个包含字段映射的附加数组,例如

$mappingArray = array('shoes' => 'dress_shoes', 'socks' => 'ankle_socks', ...);

使用此数组和前一个数组,您可以循环遍历并根据 $common 字段的值以及 $mappingArray 中的键相应地设置 SQL p>

使用示例进行编辑(可能不是最优化的):

$finalArray = array();

foreach ($mappingArray as $key => $value) {
   $finalArray[$value] = in_array($key, $common) ? 'yes' : 'no';
}

$finalArray 现在将为与您的数据库表匹配的每个值提供是/否语句。

编辑以包含 PDO:我实际上会按如下方式更新上述循环:

$finalArray = array();
$sql = "INSERT INTO cloths (" . implode(",", array_values($mappingArray)) . ") VALUES (:" . implode(",:", array_values($mappingArray)) . ")";;
foreach ($mappingArray as $key => $value) {
    $finalArray[":" . $value] = in_array($key, $common) ? 'yes' : 'no';
}

$q = $conn->prepare($sql);
$q->execute($finalArray);

与这个一起飞行,所以类似的事情......

关于MySql - 将数组值(匹配和不匹配)插入数据库匹配列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12548296/

相关文章:

mysql - MySQL 中 IF 和 THEN 的正确语法是什么?

mysql - 支持多语言的数据库的理想编码设置是什么?

mysql - 2个不同数据库之间的表模式转换

c# - 嵌套数组循环迭代

c++ - For 循环条件(整数 vector )。如何获取之前的值?

javascript - 如何从mysql数据在php中绘制树结构?

javascript - 简洁的javascript获取特定键的所有唯一值

php - JavaScript 对象对关联数组(又名 map )有效吗?有哪些选择?

r - 在R中的for循环内运行函数时中断for循环

arrays - 如何创建 n 个随机长度的字符串,其总和等于给定的数量?