我具有用于图像库的此表单数据,并使用jquery为每个新图像添加动态输入(添加删除输入字段):
<div class="row-1">
<input type="hidden" name="list_item_image_large[]" value="">
<div class="form-group col-md-12">
<input type="text" class="form-control name="list_item_title[]" value="">
</div>
<div class="form-group col-md-12">
<input type="text" class="form-control name="list_item_image_description[]" value="">
</div>
<div class="form-group col-md-12">
<input type="text" class="form-control name="list_item_image_photographer[]" value="">
</div>
<div class="form-group col-md-12">
<input type="text" class="form-control name="list_item_image_copyright[]" value="">
</div>
</div>
<div class="row-2">
<input type="hidden" name="list_item_image_large[]" value="">
<div class="form-group col-md-12">
<input type="text" class="form-control name="list_item_title[]" value="">
</div>
<div class="form-group col-md-12">
<input type="text" class="form-control name="list_item_image_description[]" value="">
</div>
<div class="form-group col-md-12">
<input type="text" class="form-control name="list_item_image_photographer[]" value="">
</div>
<div class="form-group col-md-12">
<input type="text" class="form-control name="list_item_image_copyright[]" value="">
</div>
</div>
现在提交后,我有以下数据:
Array
(
[list_item_image_large] => Array
(
[0] => uploads/images/posts/1586075502_3460aaee4378986bf677.jpg
[1] => uploads/images/2020/04/1585774613_c2f7ed8d8b0458271371.png
)
[list_item_title] => Array
(
[0] =>
[1] =>
)
[list_item_image_description] => Array
(
[0] =>
[1] =>
)
[list_item_image_photographer] => Array
(
[0] =>
[1] =>
)
[list_item_image_copyright] => Array
(
[0] =>
[1] =>
)
)
现在,我需要为mysql数据库中的每个图像插入图像数据(标题,描述,摄影师,版权)。怎么插入?!
答案 0 :(得分:0)
执行此操作的最佳方法是使用不同的结构。
Array
(
[0] => Array
(
[list_item_title] => value
[list_item_image_description] => value
[list_item_image_photographer] => value
[list_item_image_copyright] => value
)
[1] => Array
(
[list_item_title] => value
[list_item_image_description] => value
[list_item_image_photographer] => value
[list_item_image_copyright] => value
)
)
使用这种结构,您可以简单地使用for(each)循环
for($i=0; $i<count($array); $i++) {
// mysql_stuff, can access field values like this: $array[$i]['list_item_title']
}
但这需要在html输入字段上使用不同的命名。
<input type="text" class="form-control name="image[0][list_item_title]" value="">
...
<input type="text" class="form-control name="image[1][list_item_title]" value="">
...
重复字段的逻辑含义会有所不同,但是提交后处理数据将变得更加容易。
答案 1 :(得分:0)
首先将数据汇总到各个项目中。这样的事情(存在更奇特的方式):
$items = [];
foreach($data['list_item_image_large'] as $num => $val) {
$item[$num] = [
'list_item_image_large' => $val,
'list_item_title' => $data['list_item_title'][$num],
'list_item_image_description' => $data['list_item_image_description'][$num],
'list_item_image_photographer' => $data['list_item_image_photographer'][$num],
'list_item_image_copyright' => $data['list_item_image_copyright'][$num]
];
}
var_dump($items); // See what you got there
您遵循上面的代码的工作原理,对吗?之后,使用与MySQL交互的首选方法将数据插入数据库应该足够容易。我认为您通常知道如何插入数据,并且您只是在努力处理数据的结构。