douzhongpi9734 2012-11-20 17:24
浏览 51
已采纳

$ _POST和变量索引

I have a project where I create hidden input values with jQuery. These represent groups and members so I have one array for the groups themselves and arrays with the members of each groups.

For example after a few creations the code in the form includes

<input type="hidden" name="groups['group_2']" value="0">
<input type="hidden" name="groups['group_1']" value="0">
<input type="hidden" class="mem_id_holder" name="group_1[]" value="FWNGVISkjW">
<input type="hidden" class="mem_id_holder" name="group_1[]" value="G0t9E3C0yG">
<input type="hidden" class="mem_id_holder" name="group_2[]" value="NT-JEDVCS9">

for an example of 2 groups with 2 members in group_1 and 1 member in group_2.

Now, after the submit my code to iterate through the values I use this code:

if ($groups_no && isset($_POST['groups']) && !empty($_POST['groups'])){
    $groups = $_POST['groups'];
    foreach ($groups as $key => $val){
        if (isset($_POST[$key]) && !empty($_POST[$key])){
            $group_members = $_POST[$key];      
            foreach ($group_members as $member_key => $member_val){
                echo 'Actions to be done here!';
            }
        }
    }
}

The problem I have is that I get the following warning and the program fails:

Notice: Undefined index: 'group_1' in C:\ ... .php on line 31
Warning: Invalid argument supplied for foreach() ...
Notice: Undefined index: 'group_2' in C:\ ... .php on line 31
Warning: Invalid argument supplied for foreach() ...

When I use $_POST['group_1'] everything works fine but since I do not know how many and which groups I will have to insert I need the variable. I have tried some different things suggested via some Google results but nothing worked.

Any ideas? Is $_POST even capable of having variables as indexes? Also if it isn't, is there any other workaround?

  • 写回答

2条回答 默认 最新

  • dongliao6777 2012-11-20 17:27
    关注

    In your HTML, don't put quotes around the array indexes.

    <input type="hidden" name="groups[group_2]" value="0">
    <input type="hidden" name="groups[group_1]" value="0">
    <input type="hidden" class="mem_id_holder" name="group_1[]" value="FWNGVISkjW">
    <input type="hidden" class="mem_id_holder" name="group_1[]" value="G0t9E3C0yG">
    <input type="hidden" class="mem_id_holder" name="group_2[]" value="NT-JEDVCS9">
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器