PHP表单提交到多维数组

时间:2018-01-21 16:12:09

标签: php arrays

我正在编写一个代码,从中将值存储到多维数组中,但问题是当我提交表单时,我无法做到这一点,就像这样生成一个单独的数组。

Array (
    [0] => inputbox value
    [1] => 1
)

但我想要一个像这样的结果

Array (
    [0] => Array (
        'nameField' => 'inputbox value',
        'PageField' => 1
    ),
    [1] => Array ( ... ),
    [2] => Array ( ... ) ... and so on
)

我无法弄清楚我在做错的代码

<?php
    if ($_POST) : 
        echo "<pre>";
            print_r($_POST['mc']);
        echo "</pre>";
    endif;
?>

这是我的HTML

<form action="#" method="post">
<table style="width:100%">
    <thead>
        <tr>
        <td style="width:70%"><strong>Display Title Name:</strong></td>
        <td style="width:30%"><strong>Select Sub Page:</strong></td>
        </tr>
    </thead>
    <tbody>
    <tr>
    <td style="width:70%"><input name="mc[]nameField" value="" style="width:100%" type="text"></td>
    <td style="width:30%">
        <select name="mc[]PageField" style="width:100%">
            <option selected="selected" disabled="disabled" value="">Select page</option>
            <option value="1">04:00 PM Result Page</option>
            <option value="2">08:00 PM Result Page</option>
            <option value="3">11 55 AM Result Page</option>
            <option value="4">About Us</option>
            <option value="5">Contact Us</option>
        </select>
    </td>
    </tr>
    </tbody>
</table>
<div style="width:100%; padding:5px;">
    <input class="add_new_media button button-primary button-large" id="publish" value="Add" type="button">
    <input class="remove button button-primary button-large" id="publish" value="Remove" type="button">
</div>
<input name="SubmitForm" type="submit" value="SubmitForm" />
</form>

这是我的Jquery代码

<script>
jQuery(document).ready(function($){
var count = $("tbody tr").length;
myFunction(count);
    $('.add_new_media').on('click', function() {
        $('tbody tr:first-child')
        .clone()
        .appendTo($('tbody'))
        .find('input')
        .val('')
        var count = $("tbody tr").length;
        myFunction(count);
    });
    $('.remove').on('click', function() {
        $('tbody tr:last').remove();
        var count = $("tbody tr").length;
        myFunction(count);
    });
    function myFunction(count) {
        if (count > 1) {
            $('.remove').removeAttr("disabled");    
        } else {
            $('.remove').attr("disabled", "disabled");
        }
    }
});
</script>

1 个答案:

答案 0 :(得分:2)

您想要将一组字典发送到服务器。

首先,创建一个包含字典的数组,将var arrays = []称为全局变量。

var arrays = [];

一般的想法是,每当用户完成输入数据时,您需要将该数据添加到arrays

添加一个按钮,让jQuery知道何时添加到arrays

<button id="abutton" type="button" >Click Me!</button>

以下是在jQuery中将数据添加到数组的方法:

 $("#abutton").click(function(){

       var nameFieldData = // get data from name field 
       var pageFieldData = // get data from page field

       arrays.push(
          {'nameField': nameFieldData,
           'PageField': pageFieldData});
 });

然后在准备好后将arrays发送回服务器。

相关问题