How to get key of dynamic created input fields in PHP - php

i have multiple input elements like:
<input type="text" name="attribute_name[attr_1]" placeholder="Attribute Name" class="form-control" required="">
<input type="text" name="attribute_name[attr_2]" placeholder="Attribute Name" class="form-control" required="">
..
..
Now i want to loop through all the input elements and i want to get array key also, i.e. attr_1 in this case :
i'm using the following code but it is not getting key:
foreach($request->input('attribute_name.*') as $key => $val)
{
print_r($key);
print_r($val);
}

I agree with #lagbox you have to use attribute_names instead of attribute_names.*
foreach($this->request('attribute_names') as $key => $value) {
print_r($key);
}
As the attribute_names itself an array while defining it under input box you just have to use it under foreach and you will easily get the key of each input boxes.

The short example of dynamic input :
<form action="" method="post">
<input type="text" name="attribute_name[]" value="One">
<input type="text" name="attribute_name[]" value="Two">
<input type="text" name="attribute_name[]" value="Three">
<input type="submit" value="Submit">
</form>
Then in your controller you will be able to get all attribute_name values like this :
$attribute_name = $request->attribute_name; // give you an array with values
You can get all data by a foreach loop :
foreach($request->attribute_name as $key => $value) {
echo "Key : " . $key . ", Value : ". $value . "<br>";
}
Output :
Key : 1, Value : One
Key : 2, Value : Two
Key : 3, Value : Three

You should use name 'attribute_names' to get array not 'attribute_name.*' try the following code
$requestData = $request->input('attribute_names');
foreach($requestData as $key => $val)
{
print_r($key);
print_r($val);
}

Related

convert POST array data to json format

I'm using POST Method and I want the PHP script to return the data in JSON format
//data 1:
<input type="text" value="1" name="id[]">
<input type="text" value="aa" name="name[]">
<input type="text" value="cc" name="stuff[]">
//data 2:
<input type="text" value="2" name="id[]">
<input type="text" value="dd" name="name[]">
<input type="text" value="ff" name="stuff[]">
i want result be like :
{id:1,name:"aa",stuff:"cc"},{id:2,name:"dd",stuff:"ff"}
I understand that if we use json_encode($_POST,true) i will have :
{"id":["1","2"],"name":["aa","dd"],"stuff":["cc","ff"]}
i can do that with js using get method not post
id[]=1&name[]=aa&stuff=cc&id[]=2&name[]=dd&stuff[]=ff
Check my solution
https://jsfiddle.net/cqvny3th/
Or what if we generate url from the post method using http_build_query, result is :
id[]=1&id[]=2&name[]=aa&name[]=dd&stuff=cc&stuff[]=ff
But my solution works only with :
id[]=1&name[]=aa&stuff=cc&id[]=2&name[]=dd&stuff[]=ff
Regards
Definitely less elegant than #Don't Panic's solution, but in case you want/need to keep your name attributes as they are, this will work:
//prep
$repeated_post_vars = ['id', 'name', 'stuff'];
$arr = [];
//find which column has the most values, just in case they're not all equal
$num_items = max(array_map(function($col) {
return !empty($_POST[$col]) ? count($_POST[$col]) : 0;
}, $repeated_post_vars));
//iterate over value sets
for ($g=0; $g<$num_items; $g++) {
foreach($repeated_post_vars as $col)
$tmp[$col] = !empty($_POST[$col][$g]) ? $_POST[$col][$g] : null;
$arr[] = $tmp;
}
So if $_POST on submit looks like:
[
'id' => [1, 2],
'name' => ['foo', 'bar'],
'stuff' => [3]
];
The code produces:
[{"id":1,"name":"foo","stuff":3},{"id":2,"name":"bar","stuff":null}]
Rename your inputs, if you can.
<input type="text" value="1" name="data1[id]">
<input type="text" value="aa" name="data1[name]">
<input type="text" value="cc" name="data1[stuff]">
<input type="text" value="2" name="data2[id]">
<input type="text" value="dd" name="data2[name]">
<input type="text" value="ff" name="data2[stuff]">
That will group the data properly. Use array_values before json_encode so you'll get an array of objects rather than an object.
echo json_encode(array_values($_GET));
Could you do something like this?
$list = array();
for ($i=0; $i<count($_POST['id']); $i++) {
$item = new stdClass();
foreach ($_POST as $key => $values)
$item->{$key} = $values[$i];
$list[] = $item;
}
print json_encode( $list );

pairing input same name array in PHP

I have two inputs as follows:
<form method="post" action="#">
<input type="text" name="prod[][prod]"><input type="text" name="prod[][qty]">
<input type="text" name="prod[][prod]"><input type="text" name="prod[][qty]">
/* The second input set was generated dynamically via jQuery. */
</form>
I want to pair each product with its' quantity with multidimensional array with following codes (thanks to #Styphon):
$works = $_POST['prod'];
foreach ($works as $work => $value) {
echo $value['prod'] ." ". $value['qty'] ."<br>";
}
However, the results was weird as follows
aa
11
bb
22
Appreciated if someone can help on this.
You need a multidimensional array. Something like this:
<form>
<input type="text" name="prods[0][prod]">
<input type="text" name="prods[0][qty]">
<input type="text" name="prods[1][prod]">
<input type="text" name="prods[1][qty]">
</form>
Then in PHP you can access the multidimensional array using $_POST['prods'], you can loop through each one using a foreach like this:
foreach ( $_POST['prods'] as $i => $arr )
{
echo "$i is prod {$arr['prod']} and qty {$arr['qty']}<br>";
}

How to get 2 value form input array into PHP array

I have an input :
<input type="text" name="input['.$opt_id.']">
and I can get $opt_id value on php side with :
foreach ($_POST['input'] AS $key => $value)
{
$opt_id=$value;
}
but I want to get second value like this :
<input type="text" name=input"['.$opt_id.']['.$lang_id.']">
How can I get $opt_id and $lang_id? I want to insert them on different columns in the database.
Assuming that you don't have 2 entries having the same opt_id and lang_id then you can use a single key instead of 2:
HTML:
<input type="text" name="input[<?php echo "{$opt_id}_{$lang_id}"; ?>]" />
PHP:
foreach ($_POST['input'] as $optIdAndLangId => $value) {
list($opt_id, $lang_id) = explode('_', $optIdAndLangId);
}
Within HTML markup you should insert PHP variables or any other PHP code in such way:
<input type="text" name="input[<?php echo $opt_id; ?>]">
...
<input type="text" name=input"[<?php echo $opt_id; ?>][<?php echo $lang_id; ?>]">
Try Like This
you can process the data with something like this:
<?php
foreach($_POST['input'] as $key => $opt_id){
foreach($opt_id as $ans=>$lang_id){
echo 'option id :'.$ans.' Lang Id : '.$lang_id;
}
}

How do I access two arrays from a form simultaneously in php?

I receive two arrays from a form. In the .php file, I need to insert the values of each array into a column of the table.
- use the foreach loop to access the elements of one array and complete the insertion for only one column. When I do the same thing for the next array, I find that the corresponding first column elements are null in each row while for the first array, the corresponding second column elements are null. Is there anyway to avoid this and insert the array elements one after the other?
- I understand that foreach cannot be applied to two arrays so is there any other way I can access both the arrays simultaneously for insertion into a table?
Thanks.
You can use a foreach loop:
foreach($_POST['someField_1'] as $key => $value)
{
$fieldOne = $value;
$fieldTwo = $_POST['someField_2'][$key];
}
Obviously change the _POST variables to whatever you've named the fields.
As long as your field names are named something like: name="someField_1[]" and name="someField_2[]" You can use the foreach loop in this way.
EDIT
Take this HTML for your input form:
Forename: <input type="text" name="forename[]"> Surname: <input type="text" name="surname[]">
Forename: <input type="text" name="forename[]"> Surname: <input type="text" name="surname[]">
Forename: <input type="text" name="forename[]"> Surname: <input type="text" name="surname[]">
So that form allows you to enter forenames and surnames for up to 3 people. Each field has the exact same name: forename[] and surname[]
To retrieve each of the values, you would use this PHP:
foreach($_POST['forename'] as $key => $forename)
{
echo 'Forename: ' . $forename;
echo ' ';
echo 'Surname: ' . $_POST['surname'][$key] . '<br />';
}
This works because when you submit a field like forename[], with square brackets at the end, PHP will automatically convert this to an array. $key is a number which starts at 0, and goes on for however many fields there are.
PHP uses the $key to retrieve the correct fields. You could also write your HTML like this:
Forename: <input type="text" name="forename[0]"> Surname: <input type="text" name="surname[0]">
Forename: <input type="text" name="forename[1]"> Surname: <input type="text" name="surname[1]">
Forename: <input type="text" name="forename[2]"> Surname: <input type="text" name="surname[2]">
You see I've put a number between the square brackets? PHP will detect this and loop through the arrays.
You could even use a for loop:
for($i = 0; $i<count($_POST['forename']); $i++)
{
echo 'Forename: ' . $_POST['forename'][$i];
echo 'Surname: ' . $_POST['surname'][$i];
}

Getting $_POST values from array of input elements

I have an array of inputs similar to below
<input name="attr[]" value = "a" type="text" />
<input name="attr[]" value = "b" type="text" />
<input name="attr[]" value = "c" type="text" />
On the server side I am using a foreach loop to fetch the value entered. However, I want the values a ,b and c as well. How do i do that in PHP?
I did something like this but its not working for me. The $key returned is just an index.
foreach($_POST['attr'] as $key=>$val)
{
//process each $key and $val
}
use this code for retrieving values
foreach($_POST['attr'] as $key=>$val)
{
echo $val;
}

Categories