0

I want to put my post array into array array. I have the following form (this form is inside a foreach loop) which will post array data like the following:

<input type="hidden" name="cl[]" value="">
<input type="hidden" name="cd[]" value="">

and the post array contains when viewed in firebug:

cl[]    4
cl[]    4
cd[]    John
cd[]    Shaw

and I want these value in one single like below:

$allData = array(
    array(
        'cl' => 4,
        'cd' => 'John',
    ),
    array(
        'cl' => 4,
        'cd' => 'Shaw',
    )
);

Please help.

1
  • how are these input elements rendered? are they dynamic? (add new row button) or this structure is static? (html form is hardcoded) Commented Apr 8, 2015 at 6:03

2 Answers 2

1

For easy access name the array (optional)

<input type="text" name="data[cl][]" />
<input type="text" name="data[cd][]" />
<input type="text" name="data[cl][]" />
<input type="text" name="data[cd][]" />

Loop with a double foreach:

foreach($_POST['data'] as $key => $row) {
        foreach($row as $subkey => $values) {
                $array[$subkey][$key]   =   $values;
            }
    }

 print_r($array); ?>

Gives you:

Array
(
    [0] => Array
        (
            [cl] => val1
            [cd] => val2
        )

    [1] => Array
        (
            [cl] => val3
            [cd] => val4
        )

)
Sign up to request clarification or add additional context in comments.

1 Comment

You really save my day. Works fine.
0
$cl[] =   4;
$cl[]  =  4;
$cd[]   = 'John';
$cd[]    ='Shaw';
if (!empty($cl) && !empty($cd)) {
    $count = count($cl);
    for ($i = 0; $i < $count; $i++) {
        $newArr[] = array('c1' => $cl[$i], 'cd' => $cd[$i]);
    }
}
print_r($newArr);

1 Comment

for loop is faster than foreach which I have already used. I don't thing any modification is there to speed up.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.