【问题标题】:Creating multidimensional array from dynamic form in JQuery在 JQuery 中从动态表单创建多维数组
【发布时间】:2015-09-17 17:45:42
【问题描述】:

我正在尝试从输入中捕获值并将它们放入 JQuery 对象中,而不必处理 PHP 索引。

这是表格

<form name="second_form" id="second_form" action="#" method="POST">         
    <a href="#" id="AddChampion" onclick="return false;">Add Champion</a>
        <div id="ChampionInput">
        </div>
        <br><br>
        <input id="obj" type="hidden" name="obj">
        <input type="submit" name="submit">
    </form>

我试图用来重新创建数组的脚本:

$("#second_form").submit(function(event) {   
    var object = [];        
    $('.Champion').each(function() {
        var champion = {
            'name': $(this).find(".ChampionInput").val(),
            'change': $(this).find("input:radio:checked").val(),
            'General_Description': [],
            'General_Change':[]
        };
        $(this).find('.GeneralChange').each(function() {            champion.General_Description.push($(this).children(".GeneralChangeDescription").val());
            champion.General_Change.push($(this).children(".General_Change").val());
        });         
        object.push(champion);
    });
    object = JSON.stringify(object);
    $('#obj').val(object); //Sending object to hidden input   
});

这是我用来创建这个 PHP 数组的方式,当我在创建表单时删除一些输入时会弄乱索引

 foreach($_POST['champion'] as $champion){
                if(isset($_POST['Release'][$ChampionNumber])){
                    $_POST['Release'][$ChampionNumber]=='New' ? $champions[$champion]['New']=1 : $champions[$champion]['New']=0;

                    $_POST['Release'][$ChampionNumber]=='Rework' ? $champions[$champion]['Rework']=1 : $champions[$champion]['Rework']=0;

                }
                if(!empty($_POST['GeneralChangeDescription'][$ChampionNumber])){
                    foreach($_POST['GeneralChangeDescription'][$ChampionNumber] as $indexGeneral=>$GeneralChangeDescription){
                    $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] =ucfirst(trim($GeneralChangeDescription));
                    if(substr($GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1], -1)!='.'){
                        $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] = $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1].'.';
                    }
                    $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] = preg_replace('/\s\/\s/','/',$GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1]);
                    $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] = preg_replace( '/(\.?\d\/?%?)+/', '<strong>$0</strong>', $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1]);
                    $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] = preg_replace( '/\b\w+\.(jpg|png|gif)/', '', $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1]);                   
                    $champions[$champion]['General']['Change'][] =  $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1];
                    $champions[$champion]['General']['Type'][] = $_POST['GeneralChange'][$ChampionNumber][$indexGeneral];

                    }
                }

                $ChampionNumber++;              
            }

移除冠军

$('div#ChampionInput').on('click', 'a.Remove',function(){
    var champion = $(this).closest('.Champion');
    var id = champion.data("id");
    var nextChampion = champion;

    while((nextChampion = nextChampion.next()).length != 0){

        nextChampion.attr("data-id",id++);
        nextChampion.children('.ChampionInput').attr('placeholder','Champion '+ id);

    }
    championNumber=id+1;
    championNumberArray=id;
    champion.remove();
});

删除更改

$('div#ChampionInput').on('click', 'a.RemoveGeneralChange',function(){
        $(this).closest('.GeneralChange').remove();
    });

这是我的数组在 PHP 中的样子:http://i.imgur.com/rURnNTG.png,我希望在通过表单中的隐藏输入发送 JQuery 对象并在 PHP 中获取它之后让数组看起来像这样。这是我的 JQuery 对象现在的样子http://imgur.com/2r9iyKN,它甚至不接近。

这里也是表单创建的JSfiddle:jsfiddle.net/g50zd384/

【问题讨论】:

  • 生成的 jQuery 对象中有什么错误?在 PHP 中获取您的数据并在 PHP 中修改您的数组。您不能在 JSON 对象和 PHP 数组中创建相同的语法。
  • @Sim 谢谢你的回复,语法的问题是我后来用来显示这个数据/保存这个数据的代码正在使用那个多维 PHP 数组,所以我想实现类似的东西所以我不必更改其余的代码。

标签: javascript php jquery arrays multidimensional-array


【解决方案1】:

如果您确实需要该数组,请在发送表单后在 PHP 中创建它:

$array;
for($i = 1; $i <= count($_POST['champion']); $i++) {
    $champion = $_POST['champion'][$i];
    $array[$champion]['General'] = $_POST['GeneralChangeDescription'][$i];
    $array[$champion]['Type'] = $_POST['GeneralChange'][$i];
    $array[$champion]['Release'] = $_POST['Release'][$i];
}

您的表单应使用以下名称创建:

championNumber = 1;
    championNumberArray = 0;
    $('a#AddChampion').on('click',function(){
        $('div#ChampionInput').append(
        '<div class="Champion">\
             <br>\
             <input type="text" class="ChampionInput" name="champion['+championNumber+']" placeholder="Champion '+championNumber+'">\
             <datalist id="champions"></datalist>\
             <input type="radio" name="Release['+championNumber+']" value="New">New\
             <input type="radio" name="Release['+championNumber+']" value="Rework">Rework\
             <input type="radio" name="Release['+championNumber+']" value="None" checked>None\
             <a href="#" class="AddGeneralChange" data-id="'+championNumber+'" onclick="return false;">Add General Change</a>\
             <div class="GeneralChanges">\
             </div>\
             <br>\
         <div>');
        championNumber++;
    });
    $('div#ChampionInput').on('click','a.AddGeneralChange', function(){
        var id = $(this).data('id');
        $(this).siblings('.GeneralChanges').append(
           '<div class="GeneralChange">\
                <textarea type="text" size="20" rows="3" cols="50" maxlength="500" class="GeneralChangeDescription" name="GeneralChangeDescription['+id+'][]" placeholder="Enter General Change Description"></textarea>\
                <select class="General_Change" name="GeneralChange['+id+'][]">\
                   <option value="buff">Buff</option>\
                   <option value="nerf">Nerf</option>\
                   <option value="new">New</option>\
                   <option value="change">Change</option>\
                   <option value="bugfix">Bugfix</option>\
                </select>\
            </div>');
    });

以这种方式命名输入很重要! ..不是最好的方法,但比以隐藏的输入形式发送 json 数据要好。我希望这可以帮助你。

【讨论】:

  • 好吧,但是如果有人说创建 3 个冠军 [0] [1] [2] 并为每个冠军添加 1 个常规更改,那么会发生什么 [0][0] [1] [0] [2][0] 然后他会删除第二个冠军,这会弄乱数组,因为它将是 [0][0] 和 [2][0] 而不是 [0][0] 和[1][0]
  • 我在这篇文章中添加了删除冠军的功能,并在删除冠军时修复了索引,因此 [0] [1] [2] 如果您删除中间一个索引将是 [0] [1] 但它不适用于 2 维的子类别/更改
猜你喜欢
  • 2022-01-02
  • 1970-01-01
  • 2012-07-29
  • 1970-01-01
  • 1970-01-01
  • 2018-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多