将数组插入到单独的行 MySQL


INSERT array into separate rows MySQL

我有一个动态矩阵框,用户可以在其中无限使用药物,数据是这样的:

 [addindividuals] => [{"Drug":"Calpol","Strength":"100mg","Form":"Liquid","Quantity":"1"},{"Drug":"Paracetamol","Strength":"200mg","Form":"Tablet","Quantity":"16"}]

我试图实现的是将每一行插入到新行 (MySQL) 中并插入到它们的相关列中,如下所示:

: | 药物 | 实力 | 表格 |数量

行 1 |卡尔波尔 |100毫克 |液体 |1

第 2 行 |扑热息痛 |200毫克 |平板电脑 |16

我猜它是使用分解函数>(我是新手),然后 sql 插入字符串?

如果你有值作为 json 字符串集合,首先你需要爆炸,然后字符串,然后使用 a for each 遍历每个字符串,然后使用另一个为每个字符串制作单行。请提供以下代码,这可能会对您有所帮助。

$addindividuals = '{"Drug":"Calpol","Strength":"100mg","Form":"Liquid","Quantity":"1"},{"Drug":"Paracetamol","Strength":"200mg","Form":"Tablet","Quantity":"16"}';
$exploded_array = explode('},',$addindividuals);
$final_query = "INSERT INTO `table_name` (`Drug`,`Strength`,`Form`,`Quantity`) VALUES ";
$exploded_array[0] = $exploded_array[0].'}';
foreach($exploded_array as $exploded_element)
{
$single_row = '(';
$json_decode = json_decode($exploded_element,true);
foreach($json_decode as $key => $value)
{
    $single_row .= "'$value',";
}
$single_row = substr($single_row,0,-1);
$single_row .= '),';
$final_query .= $single_row;
}
$final_query = substr($final_query,0,-1);
echo $final_query;