将像 abc[0] 这样的 HTML 元素名称转换为 php 中的数组

试图将传入的表单值从 Ajax 转换为 Php 数组,但它似乎表现得像字符串


使用下面的正则表达式,如果我手头有输入名称,我可以通过循环手动替换键,但我认为这不是最好的方法,请提出建议


preg_match('/^A\[\d+\]/', $key);

preg_match('/^B\[\d+\]/', $key);

我的表格是这样的


<input type="text" id="c[0]" name="c[0]" value="">

这是我从 Ajax 到 PHP 的传入表单值的样子


Array

(

    [A[0]] => Test1

    [B[0]] => Test2

    [C[0]] => Test3

    [D1[0]] => Test4

    [A[1]] => Test1

    [B[1]] => Test2

    [C[1]] => Test3

    [D1[1]] => Test4

)

我想将传入的值转换为如下所示的 php 数组


A[0] = Test1

A[1] = Test1

B[0] = Test2

B[1] = Test2


慕丝7291255
浏览 146回答 1
1回答

缥缈止盈

使用 json_encode 将表单元素发送到 Ajax,因此必须对传入进行解码,然后 parse_str 完成这项工作,将字符串转换为数组,无法避免 foreach 循环&nbsp; &nbsp; &nbsp; &nbsp; $p2 = json_decode($_GET['form_ele1'], true);&nbsp; &nbsp; &nbsp; &nbsp; $p4 = array();&nbsp; &nbsp; &nbsp; &nbsp; foreach($p2 as $key => $value){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $tkey = $key;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; parse_str($tkey, $arr);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; foreach($arr as $key2 => $value2){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $p4[$key2][key($value2)] = $value;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $p2 = $p4;
打开App,查看更多内容
随时随地看视频慕课网APP