Skip to content
Advertisement

Convert HTML element name like abc[0] to array in php

Trying to convert incoming Form values from Ajax to a Php Array, but it seems to be behaving like strings

With the below reg ex if i have the input name handy, I may be able to manually replace the keys through a loop, but I don’t think that would be the best approach, please suggest

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

My form is something like this

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

This is what my incoming form value from Ajax to PHP looks like

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
)

I would like to convert the incoming values to a php array like the below

A[0] = Test1
A[1] = Test1
B[0] = Test2
B[1] = Test2

Advertisement

Answer

Was sending form elements to Ajax with json_encode, so had to decode on incoming, then parse_str did the job, converted the strings to array, could not avoid the foreach loops

        $p2 = json_decode($_GET['form_ele1'], true);

        $p4 = array();
        foreach($p2 as $key => $value){
            $tkey = $key;
            parse_str($tkey, $arr);
            foreach($arr as $key2 => $value2){
                $p4[$key2][key($value2)] = $value;
            } 
        } 
        $p2 = $p4;
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement