azrull
azrull

Reputation: 59

How to get desired multidimensional array with dynamic form?

I want to get desired multidimensional array as follows:

array (
  array (abc => 'a', def => 1),
  array (abc => 'b',def => 2)
)

But unable to get idea how to build its form. Help me on this guys.

I tried to build form as follows with expectation to get the above results.

<form method="POST" action="test.php">
<textarea name="test[][abc]"></textarea>
<input type="text" name="test[][def]">
<textarea name="test[][abc]"></textarea>
<input type="text" name="test[][def]">
// the 2nd set of textarea and input was dynamically generated by jQuery
<input type="submit">
</form>

Apologize if earlier questions not completed for you guys to understand.

UPDATED :

After certain modification on HTML I successfully get an array as follows:

Array
(
    [scope] => Array
        (
            [0] => iusd
            [1] => aishsadf
        )

    [qty] => Array
        (
            [0] => 723186
            [1] => 324
        )

)

How to access the value and pair it?

Upvotes: 0

Views: 484

Answers (2)

JYoThI
JYoThI

Reputation: 12085

you need to specify same index(key) for both texteara and textbox pair unless each data push into new index like this

array (
       array (abc => 'a'),
       array (def => 1),
       array (abc => 'b'),
       array (def => 2)
      )

So form should be like this

<form method="POST" action="test.php">
 <textarea name="test[0][abc]"></textarea>
 <input type="text" name="test[0][def]">
 <textarea name="test[1][abc]"></textarea>
 <input type="text" name="test[1][def]">
 <input type="submit">
</form>

OUTPUT

`array (
          array (abc => 'a', def => 1),
          array (abc => 'b',def => 2)
      )`

Upvotes: 1

melkawakibi
melkawakibi

Reputation: 881

Gather the values in an multidimensional array by giving the input fields a name with [][]. Let the post request post to the same file for testing purposes. Print the values out by creating a nested foreach statement.

//filename = post.php
<form action="post.php" method="post">
    <label>field1</label>
    <input type="text" name="array[0][value1]">
    <label>field2</label>
    <input type="text" name="array[1][value2]">

    <input type="submit" value="submit">
 </form>

 <?php

    if(isset($_POST)){
      $array = $_POST['array'];

      foreach($array as $key => $array2){
         foreach($array2 as $key => $value){
            echo $value;
         }       
      }
    }
?>

Upvotes: 0

Related Questions