dts777777 2014-12-11 00:45
浏览 27
已采纳

使用自动增量计算具有相同名称的变量

I´m still new in php and I´m having trouble in sending a form vars through POST. I use a jquery to dynamically add new fields with the same name plus a auto increment ID in a form.

In the _POST I need to have a loop to get those vars, but how am I going to get the vars count for the loop?

I have something like this:

$ID1_name = $_POST["ID1_name"];
$ID2_name = $_POST["ID2_name"];
$ID3_name = $_POST["ID3_name"];
$IDX_name = $_POST["IDX_name"];

$ID1_place = $_POST["ID1_place"];
$ID2_place = $_POST["ID2_place"];
$ID3_place = $_POST["ID3_place"];
$IDX_place = $_POST["IDX_place"];

There can be unlimited variables with same name with and AI, and I have around 10 vars like that.

How can I count by the var partial name? or Is there a better way to get those _POST? I´m using a For loop.

I was using the same name and counting in the array. It worked, but I have 3 fields with radio and 2 with checkbox, and in the array all the vars of the same name merge. So the array for food have entries from all food checkbox from the field. Does that make sense?

So in one $ID1_place = string I might have $ID1_check = array

Thanks for the help. I´know there is a easy way, but I think I´m searching the wrong way since I found nothing.

Thanks a lot. regards

  • 写回答

2条回答 默认 最新

  • duanjigua5753 2014-12-11 00:50
    关注

    There's two ways I can think for this. Either you can pass through a hidden element with the number of elements with your name, or you can use the preg_grep function to match all POST vars matching a regex pattern:

    // Search keys:
    $ID_place_keys = preg_grep('/ID[0-9]+_place/', array_keys($_POST));
    
    // Search values:
    $ID_places = preg_grep('/ID[0-9]+_place/', $_POST);
    
    // Get array of values matching keys:
    $ID_places = array_intersect_key($_POST, array_flip(preg_grep('/ID[0-9]+_place/', array_keys($_POST))));
    // Gets a bit messy with all the array functions...
    

    And here's a URL to a simple working example:

    http://ideone.com/a9AhL6

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 netty整合springboot之后自动重连失效
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击