php create array with key by html input - php

am trying to create array with key by using html input
here's my html input
<form method="post" action="">
<input type="text" name="name[][you]" value="" />
<input type="text" name="name[][he]" value="" />
<input type="text" name="name[][she]" value="" />
<input type="text" name="name[][you]" value="" />
<input type="text" name="name[][he]" value="" />
<input type="text" name="name[][she]" value="" />
<button type="submit">go</button>
</form>
my outbut is
Array ( [0] => Array ( [you] => jhon ) [1] => Array ( [he] => joy ) [2] => Array ( [she] => sarah ) [3] => Array ( [you] => samm ) [4] => Array ( [he] => petter ) [5] => Array ( [she] => susan ) )
but i want the array to be like this
Array( [0]=> array ( [you] => jhon [he] => joy [she] => sarah )[1]=> array ( [you] => pitter [he] => tom [she] => suszan ) )
is there away to do that

try like this ==>
<form method="post" action="">
<input type="text" name="name[0][you]" value="" />
<input type="text" name="name[0][he]" value="" />
<input type="text" name="name[0][she]" value="" />
<input type="text" name="name[1][you]" value="" />
<input type="text" name="name[1][he]" value="" />
<input type="text" name="name[1][she]" value="" />
<button type="submit">go</button>
</form>
OR
<form method="post" action="">
<?php $n = 2; // how many interval you want
for ($i = 0; $i < $n; $i++) {
?>
<input type="text" name="name[<?php echo $i; ?>][you]" value="" />
<input type="text" name="name[<?php echo $i; ?>][he]" value="" />
<input type="text" name="name[<?php echo $i; ?>][she]" value="" />
<?php } ?>
</form>

If you want to output an array with two children then set the keys manually, name[0] for the first three inputs and name[1] for the last three.

Everytime you write name="[][key]" php increment automatic the key.
if you write syntax like [] php increment the index of array.
Small explation
For example:
If you write an array like this
$array[] = "msg1";
$array[] = "msg2";
$array[] = "msg3";
$array length will be 2 (3 elements because it starts from 0) and it is same as
$array[0] = "msg1";
$array[1] = "msg2";
$array[2] = "msg3";
This is different from above
$array[0] = "msg1";
$array[1] = "msg2";
$array[1] = "msg3";
This array will have only 1 length (2 elements only)
Solution of your question is :
<form method="post" action="">
<input type="text" name="name[0][you]" value="" />
<input type="text" name="name[0][he]" value="" />
<input type="text" name="name[0][she]" value="" />
<input type="text" name="name[1][you]" value="" />
<input type="text" name="name[1][he]" value="" />
<input type="text" name="name[1][she]" value="" />
<button type="submit">go</button>
</form>

Related

Sort multidimensional array with different keys and values

I have a form where the user can add all the additional fields that they need.
Note: I would like to find a way to organize the code more efficiently, I will explain it in detail later.
As it is structured in HTML, I have simplified it to make it easier to understand:
<form action="" method="post">
<h1>Products</h1>
<p>
<input type="text" name="product_name[]" value="Product #1">
<input type="text" name="product_sku[]" value="pro-001">
<input type="text" name="product_price[]" value="$12.00">
<input type="text" name="product_stock[]" value="10">
</p>
<p>
<input type="text" name="product_name[]" value="Product #2">
<input type="text" name="product_sku[]" value="pro-002">
<input type="text" name="product_price[]" value="$12.00">
<input type="text" name="product_stock[]" value="10">
</p>
<p><button type="submit">Add Product</button></p>
</form>
I need to process these received data, to later work with them more easily, for example adding it to the database. But I get the code this way, a structure that doesn't make things much easier for working with that data.
Array
(
[product_name] => Array
(
[0] => Product #1
[1] => Product #2
)
[product_sku] => Array
(
[0] => pro-001
[1] => pro-002
)
[product_price] => Array
(
[0] => $12.00
[1] => $12.00
)
[product_stock] => Array
(
[0] => 10
[1] => 10
)
)
I wish I could receive the code like this:
Array
(
[0] => Array
(
[product_name] => Product #1
[product_sku] => pro-001
[product_price] => $12.00
[product_stock] => 10
)
[1] => Array
(
[product_name] => Product #2
[product_sku] => pro-002
[product_price] => $12.00
[product_stock] => 10
)
)
I have achieved it in the following way, but I want to do it in a more optimal way.
if(isset($_POST) && !empty($_POST)) {
// Total products to add
$total_products = count($_POST["product_name"]);
// Products ordered
$products_created = [];
for ($i=0; $i <$total_products ; $i++) {
$products_created[$i] = array(
'product_name' => $_POST["product_name"][$i],
'product_sku' => $_POST["product_sku"][$i],
'product_price' => $_POST["product_price"][$i],
'product_stock' => $_POST["product_stock"][$i]
);
}
echo "<pre>"; print_r($_POST);
echo "<pre>"; print_r($products_created);
}
Complete example code:
<?php
if(isset($_POST) && !empty($_POST)) {
// Total products to add
$total_products = count($_POST["product_name"]);
// Products ordered
$products_created = [];
for ($i=0; $i <$total_products ; $i++) {
$products_created[$i] = array(
'product_name' => $_POST["product_name"][$i],
'product_sku' => $_POST["product_sku"][$i],
'product_price' => $_POST["product_price"][$i],
'product_stock' => $_POST["product_stock"][$i]
);
}
echo "<pre>"; print_r($_POST);
echo "<pre>"; print_r($products_created);
}
?>
<form action="" method="post">
<h1>Products</h1>
<p>
<input type="text" name="product_name[]" value="Product #1">
<input type="text" name="product_sku[]" value="pro-001">
<input type="text" name="product_price[]" value="$12.00">
<input type="text" name="product_stock[]" value="10">
</p>
<p>
<input type="text" name="product_name[]" value="Product #2">
<input type="text" name="product_sku[]" value="pro-002">
<input type="text" name="product_price[]" value="$12.00">
<input type="text" name="product_stock[]" value="10">
</p>
<p><button type="submit">Add Product</button></p>
</form>
Solution in PHP
You could use a transpose function, that will turn your $_POST data into the desired data structure:
function transpose($array) {
foreach ($array as $key => $values) {
foreach ($values as $i => $value) $result[$i][$key] = $value;
}
return $result;
}
call as:
$products_created = transpose($_POST);
Solution in HTML
You could get the desired structure directly in PHP $_POST, if you change your HTML to this:
<form action="" method="post">
<h1>Products</h1>
<p>
<input type="text" name="product[0][name]" value="Product #1">
<input type="text" name="product[0][sku]" value="pro-001">
<input type="text" name="product[0][price]" value="$12.00">
<input type="text" name="product[0][stock]" value="10">
</p>
<p>
<input type="text" name="product[1][name]" value="Product #2">
<input type="text" name="product[1][sku]" value="pro-002">
<input type="text" name="product[1][price]" value="$12.00">
<input type="text" name="product[1][stock]" value="10">
</p>
<p><button type="submit">Add Product</button></p>
</form>
You would need some logic to inject that sequential number in the first bracket pairs in the name attributes. Assuming that this HTML is produced by PHP, it would not be hard to do that. If your HTML is dynamic on the client side, where rows can be added without interaction with the server, then you'll need to do this (also) in JavaScript.
I suppose you'll have no problem in setting that up.

html form inputs array PHP

I have a problem with my cloned form:
The form has 4 inputs and I need to separate the variables and put them together by people.
My inputs:
<input type="text" name="fName[]">
<input type="text" name="lName[]">
<input type="number" name="age[]">
<input type="text" name="city[]">
My PHP:
$fNameArray = $_POST['fName'];
$lNameArray = $_POST['lName'];
$ageArray = $_POST['age'];
$cityArray = $_POST['city'];
I really do not understand how two-dimensional arrays work, to group people to complete the form, as in the following example:
first name: siddharta, last name: naranjo, age: 29, city: mexico
first name: xxxxx, last name: xxxxxx, age: xx, city: xxxx.
Some of these answers are wrong if I understand you.
First of all if you use the naming convention data[]fname then it will not group surely?
Secondly, the blank bracket will have it constantly move to a new array.
You will end up with a load of arrays with one element in them.
You will need to number or ID the arrays to keep them together.
<?php
if(isset($_POST['data'])){
$results = $_POST['data'];
echo "<pre>";
print_r($results);
echo "<pre>";
}
?>
<form action="" method="post">
<!-- User 1 -->
<input type="text" name="data[0][fName]" value="test 1">
<input type="text" name="data[0][lName]" value="test 1">
<input type="number" name="data[0][age]" value="21">
<input type="text" name="data[0][city]" value="test 1">
<br>
<!-- User 2 -->
<input type="text" name="data[1][fName]" value="test 2">
<input type="text" name="data[1][lName]" value="test 2">
<input type="number" name="data[1][age]" value="22">
<input type="text" name="data[1][city]" value="test 2">
<br>
<!-- User 3 -->
<input type="text" name="data[2][fName]" value="test 3">
<input type="text" name="data[2][lName]" value="test 3">
<input type="number" name="data[2][age]" value="23">
<input type="text" name="data[2][city]" value="test 3">
<br>
<input type="submit" value="Go">
</form>
This produces this:
Array
(
[0] => Array
(
[fName] => test 1
[lName] => test 1
[age] => 21
[city] => test 1
)
[1] => Array
(
[fName] => test 2
[lName] => test 2
[age] => 22
[city] => test 2
)
[2] => Array
(
[fName] => test 3
[lName] => test 3
[age] => 23
[city] => test 3
)
)
Which is what it looks like you want?
Your html is ok
If i understand you right take a look at this
<?php
if($_POST && isset($_POST['fName'])) {
$people = count($_POST['fName']);
for($i=0; $i<$people; $i++) {
echo "<p>first name: {$_POST['fName'][$i]}, last name: {$_POST['lName'][$i]} ...</p>";
}
}
Use keys for 2 dimensional array.
<input type="text" name="fName[0]">
<input type="text" name="lName[0]">
<input type="number" name="age[0]">
<input type="text" name="city[0]">
<input type="text" name="fName[1]">
<input type="text" name="lName[1]">
<input type="number" name="age[1]">
<input type="text" name="city[1]">

HTML Element Arrays - Multidimensional

I'm not 100% sure of the correct terminology of what I'm even asking, but I currently have a form that is being posted that has an array of elements:
<form>
<input type="text" name="album_songs[0][title]" value="Let It Go" />
<input type="text" name="album_songs[0][writer]" value="Robert Lopez, Kristen Anderson-Lopez" />
<input type="text" name="album_songs[0][composer]" value="Frozen" />
<input type="text" name="album_songs[0][length]" value="3:44" />
<input type="text" name="album_songs[0][genre]" value="Soundtrack, Music, Animated" />
<input type="text" name="album_songs[0][songorder]" value="5" />
<input type="text" name="album_songs[1][title]" value="Love Is An Open Door" />
<input type="text" name="album_songs[1][writer]" value="Robert Lopez" />
<input type="text" name="album_songs[1][composer]" value="Frozen" />
<input type="text" name="album_songs[1][length]" value="2:07" />
<input type="text" name="album_songs[1][genre]" value="Soundtrack, Music, Animated" />
<input type="text" name="album_songs[1][songorder]" value="4" />
</form>
And in my code, I can access these elements like the following:
$songs = $_POST["album_songs"];
foreach($songs as $song) {
$title = $song["title"];
$writer = $song["writer"]; // turn into array??
$composer = $song["composer"];
$length = $song["length"];
$genre = $song["genre"]; // turn into array??
$songorder = $song["songorder"];
}
What I would like to have happen, is not only have an array of songs, but also an array of Writers and Genres. Is this even possible? I tried mocking up something like the following but it did not work:
<input type="text" name="album_songs[4][genre[0]]" value="Soundtrack" />
<input type="text" name="album_songs[4][genre[1]]" value="Music" />
<input type="text" name="album_songs[4][genre[2]]" value="Animated" />
Any suggestions or is it even possible?
I might consider a dropdown, but you almost had it:
<input type="text" name="album_songs[4][genre][]" value="Soundtrack" />
<input type="text" name="album_songs[4][genre][]" value="Music" />
<input type="text" name="album_songs[4][genre][]" value="Animated" />
Gives this:
Array
(
[4] => Array
(
[genre] => Array
(
[0] => Soundtrack
[1] => Music
[2] => Animated
)
)
)
Try to use square bracket syntax to convert your form inputs into an array.
I.E. :
<input type="text" name="album_songs_title[]" value="Title1" />
<input type="text" name="album_songs_title[]" value="Title2" />
Then, you will be able to browse your datas with a foreach().
I think it might work.

PHP Submitting array to POST fails

When i try to submit this simple test form to PHP:
<form action="test.php" method="post">
<input name ="lang_learn[0]lang" type="text" value="1"><br>
<input name ="lang_learn[0]level" type="text" value="2"><br>
<input name ="lang_learn[1]lang" type="text" value="3"><br>
<input name ="lang_learn[1]level" type="text" value="4"><br>
<input type="submit">
</form>
i expect to have in the $_POST array something like this:
Array
(
[lang_learn] => Array
(
[0] => Array ([lang] => 1, [level] => 2)
[1] => Array ([lang] => 3, [level] => 4)
)
)
instead i get this:
Array
(
[lang_learn] => Array
(
[0] => 1
[1] => 4
)
)
i tried with different installations over different servers, and i always get the same result.
where is the problem? reading around this should be the right way to do that.
The names of the input fields need fixing:
<input name ="lang_learn[0][lang]" type="text" value="1"><br>
<input name ="lang_learn[0][level]" type="text" value="2"><br>
<input name ="lang_learn[1][lang]" type="text" value="3"><br>
<input name ="lang_learn[1][level]" type="text" value="4"><br>
You need to use sub-arrays, like you would in PHP. Each key should be surrounded with [ and ]. Try this...
<form action="test.php" method="post">
<input name ="lang_learn[0][lang]" type="text" value="1"><br>
<input name ="lang_learn[0][level]" type="text" value="2"><br>
<input name ="lang_learn[1][lang]" type="text" value="3"><br>
<input name ="lang_learn[1][level]" type="text" value="4"><br>
<input type="submit">
</form>
Try this,
<form action="test.php" method="post">
<input name ="lang_learn[0][lang]" type="text" value="1"><br>
<input name ="lang_learn[0][level]" type="text" value="2"><br>
<input name ="lang_learn[1][lang]" type="text" value="3"><br>
<input name ="lang_learn[1][level]" type="text" value="4"><br>
<input type="submit">
</form>
You probably need to do this:
<form action="test.php" method="post">
<input name ="lang_learn[0][lang]" type="text" value="1"><br>
<input name ="lang_learn[0][level]" type="text" value="2"><br>
<input name ="lang_learn[1][lang]" type="text" value="3"><br>
<input name ="lang_learn[1][level]" type="text" value="4"><br>
<input type="submit">
</form>
Your syntax is not correct: name ="lang_learn[0]lang" must be name ="lang_learn[0][lang]"

INSERT multiple records in MySQL with one PHP form

INSERT multiple records in MySQL with one PHP form.
Simple Form
<form action="process.php" method="post">
<p><label>Beamline ID</label>
<input type="text" name="bline_id[][bline_id]" />
<label>Flow</label>
<input type="text" name="flow[][flow]" />
</p>
<p><label>Beamline ID</label>
<input type="text" name="bline_id[][bline_id]" />
<label>Flow</label>
<input type="text" name="flow[][flow]" />
</p>
<p><label>Beamline ID</label>
<input type="text" name="bline_id[][bline_id]" />
<label>Flow</label>
<input type="text" name="flow[][flow]" />
</p>
<p><label>Beamline ID</label>
<input type="text" name="bline_id[][bline_id]" />
<label>Flow</label>
<input type="text" name="flow[][flow]" />
</p>
<p><label>Beamline ID</label>
<input type="text" name="bline_id[][bline_id]" />
<label>Flow</label>
<input type="text" name="flow[][flow]" />
</p>
<input name="Submit" type="submit" />
</form>
//process.php
<?php
// connect to the database
include('connect-db.php');
$cnt = count($_POST['bline_id']);
$cnt2 = count($_POST['flow']);
if ($cnt > 0 && $cnt == $cnt2) {
$insertArr = array();
for ($i=0; $i<$cnt; $i++) {
$insertArr[] = "('" . mysql_real_escape_string($_POST['bline_id'][$i]) . "', '" . mysql_real_escape_string($_POST['flow'][$i]) . "')";
}
$query = "INSERT INTO bltest (bline_id, flow) VALUES " . implode(", ", $insertArr);
mysql_query($query) or trigger_error("Insert failed: " . mysql_error());
}
echo("<pre>\n");
print_r($_POST);
echo("</pre>\n");
mysql_close($connection);
?>
Array results
Array
(
[bline_id] => Array
(
[0] => Array
(
[bline_id] => 1
)
[1] => Array
(
[bline_id] => 2
)
[2] => Array
(
[bline_id] => 3
)
[3] => Array
(
[bline_id] => 4
)
[4] => Array
(
[bline_id] => 5
)
)
[flow] => Array
(
[0] => Array
(
[flow] => 11
)
[1] => Array
(
[flow] => 22
)
[2] => Array
(
[flow] => 33
)
[3] => Array
(
[flow] => 44
)
[4] => Array
(
[flow] => 55
)
)
[Submit] => Submit Query
)
the INSERT result is of course 5 rows but no data inserted for $bline_id or $flow. But looking at the array, that is the correct data.
USE PDO or Mysqli instead, these extensions have the prepare option, so you need ony to pass the query once, and that use a while loop to change the data!
<?php
// pdo example
$sql = 'INSERT INTO `table` (field1, field2, field3) VALUES (:value1, :value2, :value3)';
// $dbh is pdo connection
$insertTable = $dbh->prepare($sql);
$countArray = count($array);
$i = 0;
while ($i < $countArray) {
$insertTable->bindParam(':value1', $array[1][$i], PDO::PARAM_INT); // if value is int
$insertTable->bindParam(':value2', $array[2][$i], PDO::PARAM_STR); // if value is str
$insertTable->bindParam(':value3', $array[3][$i], PDO::PARAM_STR);
$insertTable->execute();
$i++;
}
?>
Okay. Given what you've told me, here's the solution I've thought up. I'm not going to give you code; it defeats the point of you writing it.
I would have the user type in some values into the two input text fields "bline_id" and "flow".
When they hit the submit button, those values are added to an array in the PHP code.
The array is then serialized into a string, and stored as a session cookie.
As each value is inputted, you unserialize the cookie so it is converted into an array, add the new value into the array, and repeat.
When the user hit's another button, "Store in Database". This option will unserialize the cookie, loop through each element in the array, and store each value in the database.
Also bare in mind that you have two values, bline_id and flow. These can be stored in two arrays and stored as two cookies. All it means is you're doing this process for two different arrays instead of one.
Finally, you should be using the PDO Object. I've linked you to it with the "store" link. It is the recommended method.
OMG!!!! I finally got it! It was my stupid form!
corrected below-------
<form action="process.php" method="post">
<p><label>Beamline ID</label>
<input type="text" name="bline_id[]" value="<?php echo $bline_id; ?>" />
<label>Flow</label>
<input type="text" name="flow[]" value="<?php echo $flow; ?>" />
</p>
<p><label>Beamline ID</label>
<input type="text" name="bline_id[]" value="<?php echo $bline_id; ?>" />
<label>Flow</label>
<input type="text" name="flow[]" value="<?php echo $flow; ?>" />
</p>
<p><label>Beamline ID</label>
<input type="text" name="bline_id[]" value="<?php echo $bline_id; ?>"/>
<label>Flow</label>
<input type="text" name="flow[]" value="<?php echo $flow; ?>" />
</p>
<p><label>Beamline ID</label>
<input type="text" name="bline_id[]" value="<?php echo $bline_id; ?>" />
<label>Flow</label>
<input type="text" name="flow[]" value="<?php echo $flow; ?>" />
</p>
<p><label>Beamline ID</label>
<input type="text" name="bline_id[]" value="<?php echo $bline_id; ?>" />
<label>Flow</label>
<input type="text" name="flow[]" value="<?php echo $flow; ?>" />
</p>
<input name="Submit" type="submit" />
</form>

Categories