Wasim A.
Wasim A.

Reputation: 9890

HTML Form passing two deminsion array to PHP (special case i think)

This HTML code

<input name="Html_Array[][title]">
<input name="Html_Array[][amount]">

Generate this PHP Array

    [0] => Array
            (
                [title] => Seilpendel für Tragsysteme
            )

        [1] => Array
            (
                [amount] => 2
            )...So on

What will be HTML code to Generate following PHP Array

        [0] => Array
            (
                [title] => Seilpendel für Tragsysteme
                [amount] => 1
            )

        [1] => Array
            (
                [title] => Article Tiel
                [amount] => 2
            )

Size of array is unknown so we can't hard-code index to 0,1,2 etc

Upvotes: 3

Views: 2408

Answers (4)

Tom Hallam
Tom Hallam

Reputation: 1950

Keep an index every time you add a new group of form fields (uses jQuery):

window.count = 0;
$('#add-more-button').on('click', function() {
 $('<input name="html_array[' + window.count + '][title] />').appendTo('form:first');
 $('<input name="html_array[' + window.count + '][amount] />').appendTo('form:first');
 window.count++;
});

You should get the right structure.

Edit if you mean PHP:

// Assuming 0-indexed array
foreach($my_array as $key => $value) {
 echo '<input name="html_array[' . $key . '][title]" />';
 echo '<input name="html_array[' . $key . '][value]" />';
}

Upvotes: 2

goat
goat

Reputation: 31813

 <input name="Html_Array[0][title]">
 <input name="Html_Array[0][amount]">

 <input name="Html_Array[1][title]">
 <input name="Html_Array[1][amount]">

and so on...

a loop can be used to generate the integer sequence needed.

Upvotes: 1

Yaron U.
Yaron U.

Reputation: 7881

just remove the quotation marks that wrapped the second dimension array name

 <input name="Html_Array[][title]">
 <input name="Html_Array[][amount]">

Upvotes: 0

Ry-
Ry-

Reputation: 224857

I don't think you can create that exact structure in HTML. Just merge them:

$result = array();
$current = array();

foreach($input as $item) {
    $k = reset(keys($item));

    if(isset($current[$k])) {
        $result[] = $current;
        $current = array();
    }

    $current[$item] = $item[$k];
}

Upvotes: 1

Related Questions