I try to get a PHP array like this
array(
color => array("blue", "red", "yellow", "pink"),
size => array("small", "medium, "large"),
width => array("30", "32, "34"),
);
The data is posted from a HTML form like below
<form method="post" action="post.php">
<input type="text" name="data[color][]" value="red"/>
<input type="text" name="data[color][]" value="blue"/>
<input type="text" name="data[size][]" value="small"/>
<input type="text" name="data[width][]" value="30"/>
<input type="text" name="data[width][]" value="32"/>
</form>
The problem is that only the last items are posted in the array. The output from the array is
array(
color => array("blue"),
size => array("small"),
width => array("32"),
);
Is there something missing in my form why this is happening?
CodePudding user response:
You are not submitting your POST add an submit button - Try this for example:
<form method="post" action="">
<input type="text" name="data[color][]" value="red"/>
<input type="text" name="data[color][]" value="blue"/>
<input type="text" name="data[size][]" value="small"/>
<input type="text" name="data[width][]" value="30"/>
<input type="text" name="data[width][]" value="32"/>
<input type="submit" />
</form>
<?php
echo '<pre>';
print_r($_POST); // this will only print a filled array once submit is clicked.
You'll see this if submit wasn't clicked:
Array
(
)
And this if it was :
Array
(
[data] => Array
(
[color] => Array
(
[0] => red
[1] => blue
)
[size] => Array
(
[0] => small
)
[width] => Array
(
[0] => 30
[1] => 32
)
)
)
On your post.php file - You might be printing a different array altogether because without submitting the form this data stays in the input line.... you should print : $_POST; there like in the example.
How are you even reaching there without a submit button is beyond me ...:)
CodePudding user response:
I'm still not sure what you want but how about this:
foreach($_POST["data"] as $row => $data)
{
echo("$row = " . implode(", ", $data) . PHP_EOL);
}
Will produce:
color = red, blue
size = small
width = 30, 32
OR
Just JSON encode the $_POST array. That converts the array to a string. Later you can JSON decode it to turn it back into an array.
