所以我试图使用$_POST
将动态创建的字段集保存到数据库中。基本上,我无法弄清楚如何将选项保存为每个字段集的对象,而不是作为选项本身的数组。我很难描述......让我解释一下。
首先,截图显示事物的样子here。
这些字段通过jQuery动态创建,效果很好。这是我为表单设置的字段:
<label>Calendar Name
<input name="name[]" id="name[]" type="text" value="<?php echo $calendars['name'][$key]; ?>">
</label>
<label>Public URL
<input name="url[]" id="url[]" type="text" value="<?php echo $calendars['url'][$key]; ?>">
</label>
<label>Color
<input name="color[]" id="color[]" type="text" value="<?php echo $calendars['color'][$key]; ?>">
</label>
这是similar to this question但我想我不明白我应该如何使用JS正确地提升和排序索引值,或者如果有一个PHP解决方案我只是完全缺失。
TL; DR基本上我怎么能用foo [0] ['name']来代替foo ['name'] [0],使用PHP或JS或者两者都是动态创建的形式和重复的字段集? / p>
答案 0 :(得分:0)
我会像这样发布流程:
if(isset($_POST['name'])) {
// $i is how you are going to assign your keys
$i = 0;
// Loop through post array
foreach($_POST['name'] as $key => $value) {
// Assign your new array the key values of each post array
$_rows[$i]['name'] = $_POST['name'][$key];
$_rows[$i]['url'] = $_POST['url'][$key];
$_rows[$i]['color'] = $_POST['color'][$key];
$i++;
}
/* Do some quick prints to see before and after
echo '<pre>';
print_r($_POST);
print_r($_rows);
echo '</pre>';
*/
}
答案 1 :(得分:0)
好的,所以我在我正在处理的插件中做了类似的事情,这就是我提出的解决方案。我修改了我的代码,试图匹配你想要完成的任务。
现在根据您上面的代码,我假设您有一个名为calendars
的帖子元。所以我们需要稍微修改你的代码:
// Get our saved post meta if it exists
$calendars = get_post_meta( $post_id, '_calendars', true );
// Loop through all of our calendars and display the inputs
if ( $calendars ) {
foreach ( $calendars as $calendar ) {
?>
<label>Calendar Name
<input name="name[]" id="name[]" type="text" value="<?php echo $calendar['name']; ?>">
</label>
<label>Public URL
<input name="url[]" id="url[]" type="text" value="<?php echo $calendar['url']; ?>">
</label>
<label>Color
<input name="color[]" id="color[]" type="text" value="<?php echo $calendar['color']; ?>">
</label>
<?php
}
}
在保存功能中包含以下代码:
$old_calendar = get_post_meta( $post_id, '_calendars', true );
$new_calendar = array();
$name = $_POST['name'];
$url = $_POST['url'];
$color = $_POST['color'];
// Just to get the number of calendars we have
$count = count( $name );
for ( $i = 0; $i < $count; $i++ ) {
$new_calendar[$i]['name'] = $name[$i]; // Need sanitation if desired
$new_calendar[$i]['url'] = $url[$i]; // Need sanitation if desired
$new_calendar[$i]['color'] = $color[$i]; // Need sanitation if desired
}
if ( !empty( $new_calendar ) && $new_calendar != $old_calendar )
update_post_meta( $post_id, '_calendars', $new_calendar );
elseif ( empty($new_calendar) && $old_calendar )
delete_post_meta( $post_id, '_calendars', $old_calendar );