Generate array with for loop - php

I am using CodeIgniter framework and getting values from html form.
Currently i am preparing array with fixed number of inputs, ques_X are inputs, But when ques_x numbers are increasing, i need to manually add each key pair value, like ques_11, ques_12...
$answers = array(
'ques_1' => $this->input->post('ques_1', TRUE),
'ques_2' => $this->input->post('ques_2', TRUE),
'ques_3' => $this->input->post('ques_3', TRUE),
'ques_4' => $this->input->post('ques_4', TRUE),
'ques_5' => $this->input->post('ques_5', TRUE),
'ques_6' => $this->input->post('ques_6', TRUE),
'ques_7' => $this->input->post('ques_7', TRUE),
'ques_8' => $this->input->post('ques_8', TRUE),
'ques_9' => $this->input->post('ques_9', TRUE),
'ques_10' => $this->input->post('ques_10', TRUE))
Is it possible to create something with for or foreach loops?

You can create a for loop like this:
$answers = array();
for($i = 1; $i <= 10; ++$i){
$answers['ques_'.$i] = $this->input->post('ques_'.$i, TRUE);
}

Use an array instead of ques_n naming for the inputs.
<input type="text" name="questions[]" value="value1"/>
<input type="text" name="questions[]" value="value2"/>
<input type="text" name="questions[]" value="value3"/>
and then you can just get the data like this:
$answers = $this->input->post('questions', TRUE);
Edit based on the comment of rjcod:
You can also generate the inputs like this, and still use the same php code:
<input type="text" name="questions[0]" value="value1"/>
<input type="text" name="questions[1]" value="value2"/>
<input type="text" name="questions[2]" value="value3"/>
<!-- This 3 radio buttons are grouped, you can also wrap them in
fieldset if you want -->
<input type="radio" name="questions[3]" value="1"/>
<input type="radio" name="questions[3]" value="2"/>
<input type="radio" name="questions[3]" value="3"/>

Your can try this:
$data = array();
$post_length = sizeof($_POST);
for($i = 1; $i <= $post_length; ++$i){
$data ['ques_'.$i] = $this->input->post('ques_'.$i, TRUE);
}
Or you can use this which is fully dynamic.
$data = array();
foreach($_POST as $key=>$value)
{
$data [$key] = $this->input->post($key, TRUE);
//or
//$data [$key] = $value;
}

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 );

update multiple checkbox data by using loop

There are multiple checkbox about 50+ for user access, checkbox are like follows;
<input name="PREFIX_1" type="checkbox">
<input name="PREFIX_2" type="checkbox">
<input name="PREFIX_3" type="checkbox">
...........
I have multiple checkbox with its respective values which I loop through to add/update the values in the database, which is like follows:
foreach ($_POST as $field => $value ) {
if ( preg_match('/^PREFIX_/', $field) ) {
$access = isset($value)?'1':'0';
$file = substr($field, 4);
$this->db->query('UPDATE_DESIRED_TABLE');
}
}
The problem is when I add/update the values in the database by using loop foreach ($_POST as $field => $value ) and checking the prefix, I only get values of checkbox that are checked and the values of data that are not checked are not in the $_POST data.
And, I don't get any values which are not checked, which is not even the name of that checkbox. In other words only those values are set which are checked.
Now I have to change the value of all the data in the database by comparing both the data in the database and from the post data.
How can I solve this?
You would need to send hidden inputs along with the checkboxes like this:
<form action="" method="post">
<input type="hidden" id="PREFIX_1_" name="PREFIX_1" value="0">
<input type="checkbox" id="PREFIX_1" name="PREFIX_1" value="1" />
<input type="hidden" id="PREFIX_2_" name="PREFIX_2" value="0">
<input type="checkbox" id="PREFIX_2" name="PREFIX_2" value="1" />
<input type="hidden" id="PREFIX_3_" name="PREFIX_3" value="0">
<input type="checkbox" id="PREFIX_3" name="PREFIX_3" value="1" />
<input type="submit" name="sub" value="Go" />
</form>
However you cant use the isset anymore with this, change PHP like this:
if(isset($_POST['sub']))
{
foreach ($_POST as $field => $value )
{
if ( preg_match('/^PREFIX_/', $field) )
{
$access = $value;
$file = substr($field, 4);
$this->db->query('UPDATE_DESIRED_TABLE');
}
}
}
Considering you know the number of checkbox, stored in example in $checkBoxCount, you might use this kind of loop :
for ($i = 1; $i <= $checkBoxCount; $i++)
{
$access = ((isset($_POST["PREFIX_" . $i])) ? ('1') : ('0')));
//manage DB
}

How to deal with unchecked checkbox array value without javascripts?

Suppose I have a form like this, where checkboxes are repeating fields:
<form action="" method="post">
<?php for($i=0; $i<3; $i++) { ?>
<input type="checkbox" name="ch[]" value="1">
<?php } ?>
<button type="submit" name="submit">submit</button>
</form>
I'm on WordPress and using custom meta boxes for dealing with it. So I declared the form within the callback function of the metabox, and receiving the values in another save function that's hooked with save_post and new_to_publish action hooks.
So what's happening: when I click on the button, the metabox callback submitted the form, and the hooked function receives it. (Can be visible at add_meta_box() WordPress Codex) Suppose my save function contains:
<?php
if( isset($_POST['submit']) ) {
$chb = $_POST['ch'];
$result = array();
foreach ($chb as $cb) {
$result[] = array( 'isactive' => $cb );
}
var_dump($result);
}
?>
It's showing that, checkboxes are not returning any value when unchecked. I considered all the server-side solutions mentioned here: Post the checkboxes that are unchecked
PROBLEM is, whenever the form is submitted, it's taking the checkboxes' values to an array(), so I can't check the array values like:
if( !isset( $_POST['ch'] ) || empty( $_POST['ch'] ) ) {
$chb = 0;
} else {
$chb = 1;
}
I also tried hidden field with 0 value, accompanied with array_unique(), but nothing seems work for me.
How can I deal with unchecked checkboxes in an array so that they can't be null, and my foreach can loop through all of 'em and store data accordingly, and correct?
I want to avoid JavaScripts solutions.
If you name the checkboxes with an index in them, like so:
<input type="checkbox" name="chk_<?php echo $i ?>" value="1">
Then you could loop through them like so:
<?php
$chkBoxes = array();
foreach ($_POST as $k => $v) {
if (strpos("chk_",$k) === 0) {
$cbIndex = str_replace('chk_', '', $k);
$chkBoxes[$cbIndex] = $v;
}
}
Then to test if a checkbox was checked and sent to the server, you could use:
<?php
if (isset($chkBoxes[$cbIndex]))
Remember - the value of the checkbox is only sent if it was checked: Does <input type="checkbox" /> only post data if it's checked?
Add a hidden field in the form with the number of checkboxes, and use the index $i for the array ch[]:
<form action="" method="post">
<input type="hidden" name="num" value="<?= $num = 3 ?>">
<?php for($i=0; $i<$num; $i++) { ?>
<input type="checkbox" name="ch[<?= $i ?>]" value="1">
<?php } ?>
<button type="submit" name="submit">submit</button>
</form>
Then:
<?php
if( isset($_POST['submit']) ) {
$chb = $_POST['ch'];
$num = $_POST['num'];
$result = array();
for($i=0; $i<$num; $i++) {
$result[$i]['isactive'] = isset($chb[$i]) ? 1 : 0;
}
var_dump($result);
}
?>
first of all i copied ideas from many people inside this forum! i only synthesized the way!
my function to get data from my base located inside the $anoigmata class:
function getall() {
$data = $this->_db->get('<table_name>', array('ID', '>=', 0));
$results = $data->results();
$rows = $data->count();
return array($results, $rows);
}
code inside the create function to save all the secondary options that are not presented on the site.
$fields_Κ = array('history' => serialize(array(
'checkboxes' => Input::get('checkboxes')
)),
);
$data = $this->_db->insert('ΚΕΛΥΦΟΣ', $fields_Κ);
return true;
the php-html code that shows the result
<form method="post">
<div class="form-group">
<label for="checkboxes[]">checkboxes title</label><br>
`<?php
for ($i=0; $i<$anoigmata->getall()[1]; $i++) {
echo "
<input type='hidden' name='checkboxes[$i]' value='0' />
<input type='checkbox' id='checkboxes[$i]' name='checkboxes[$i]' value='".$anoigmata->getall()[0][$i]->ΕΜΒΑΔΟΝ."' />".$anoigmata->getall()[0][$i]->ΠΕΡΙΓΡΑΦΗ."<br>";}?>`
`</div><button type="submit" class="btn btn-success">Submit</button></form>`
***ΕΜΒΑΔΟΝ and ΠΕΡΙΓΡΑΦΗ are the row names from my table that i'm saving!!!
i hope i helped a little..!

PHP: Manipulating Multdimensional Array in Form Data?

I have a form that includes the first name and last name of a person. The user can add multiple people using a link, that creates new input fields via JS. Here's an example of a form that includes 2 people:
<form action="" method="post">
<input type="text" class="required" name="people[first][]" />
<input type="text" class="required" name="people[last][]" />
<input type="text" class="required" name="people[first][]" />
<input type="text" class="required" name="people[last][]" />
<input type="submit" name="submit">
</form>
I'm trying to figure out a way to insert this data into the database. I've tried using:
foreach ($_POST['people'] as $person) {
foreach ($person as $value) {
echo $value . '<br/>';
}
}
.. which results in
first name 1
first name 2
last name 1
last name 2
I'm trying to group the results somehow so I can insert a new row for each first name x + last name x combination.
Create the input elements like this:
<input type="text" name="people[0][first]" />
<input type="text" name="people[0][last]" />
<input type="text" name="people[1][first]" />
<input type="text" name="people[1][last]" />
In your PHP:
foreach ($_POST['people'] as $person) {
echo $person['first'].' '.$person['last'].'<br />';
}
$_POST['people']['first'] is an array of first names.
$_POST['people']['last'] is an array of last names.
You can merge them into an array of arrays like this:
$people = $_POST['people'];
$length = count($people['first']);
for($i = 0; $i < $length; $i++)
$temp[] = array('first' => $people['first'][$i], 'last' => $people['last'][$i]);
$people = $temp;
The resulting array in $people will be an array of associative arrays, and might look like:
Array
(
[0] => Array
(
[first] => Jim
[last] => Smith
)
[1] => Array
(
[first] => Jenny
[last] => Johnson
)
)
which is equivalent to the array you would get by modifying your HTML as bsdnoobz has shown you can do as well. Iterating through it would be the same too:
foreach ($people as $person) {
echo $person['first'] . ' ' . $person['last'] . '<br />';
}

Get values from select items with same name

I have a HTML form with a variable number of select fields. Each select field represents the same category, so I named all the selects like mySelect[]. The code I wrote for getting the values is bellow:
for ($i = 0; $i < count($_POST['mySelect']); $i++) {
echo $_POST['mySelect'][$i];
}
But I don't get any results. What is wrong?
Thanks.
<input type="text name="item[]" value="item1" />
<input type="text name="item[]" value="item2" />
<input type="text name="item[]" value="item3" />
<pre>
<?php print_r( $_POST[ 'item' ] ); ?>
</pre>
What happens if you do:
var_dump($_POST['mySelect']);
Also, what about using foreach instead of for:
foreach ($_POST['mySelect'] as $key => $value) {
echo $value;
}

Categories