I have a form that contains some special characters as the keys.
Below is an example:
<input type="text" name="skills[React.js]" placeholder="Years" class="form-control">
<input type="text" name="skills[Responsive-Web-Design-(RWD)]" placeholder="Years" class="form-control">
When I post the form I get 0:value, 1:value
Instead of React.js:value, Responsive-Web-Design-(RWD): value
Are there any workarounds?
To get desired output, text input should be like this
<input type="text" name="skills[]"
placeholder="Years" class="form-control"
value="React.js">
<input type="text" name="skills[]"
placeholder="Years" class="form-control"
value="Responsive-Web-Design-(RWD)">
And in server side, received these values
<?php
if(isset($_POST['skills'])){
$value1=$_POST['skills'][0];
$value2=$_POST['skills'][1];
}
?>
Here's how you could do it using vanilla PHP
<?php
$topics = [
1 => 'React.js',
2 => 'Responsive-Web-Design-(RWD)'
]
?>
<?php foreach ($topics as $key => $label) { ?>
<input type="text" name="skills[<?php echo $key; ?>]" placeholder="Years" class="form-control">
<?php } ?>
The submitted request should contain:
[
'skills' => [
1 => 'first field value',
2 => 'second field value',
]
]
So to get it the way you want it:
$skills = [];
foreach($_POST['skills'] as $key => $value) {
$skills[$topics[$key]] = $value;
}
the $result array would now contain:
[
'React.js' => 'value 1',
'Responsive-Web-Design-(RWD)' => 'value 2'
]
Related
I am having a $_POST array look like this:
Array
(
[veryfy_doc_type] => Array
(
[0] => 1
[1] => 2
)
[id_number] => Array
(
[0] => 3242424
[1] => 4456889
)
[document_issuer] => Array
(
[0] => 1
[1] => 3
)
[verify_doc_expiry_date] => Array
(
[0] => 2016-01-26
[1] => 2015-02-20
)
[doc_id] => Array
(
[0] => 15
[1] => 16
)
[user_id] => Array
(
[0] => 14
[1] => 14
)
)
Using this array I need to get each values into php variables.
I tried it something like this, but it doesn't work for me.
foreach($_POST AS $k => $v) {
//print_r($v);
list($doc_type, $id_number, $issuer, $expiry_date, $doc_id, $user_id) = $v;
}
echo "Type = $doc_type";
Can anybody tell me how to figure this out.
Thank you.
This might help you since you can also use extract in php to create variables.
<?php
$_POST = array(
'veryfy_doc_type'=> array(1,2),
'id_number' => array(3242424,4456889),
'document_issuer'=> array(1,3),
'verify_doc_expiry_date'=> array('2016-01-26','2015-02-20'),
'doc_id' => array(15,16),
'doc_id' => array(14,14)
);
extract($_POST);
print_r($veryfy_doc_type);
print_r($id_number);
So you want to reference each of the sub-array values while looping the main array... maybe something like this?
// Loop one of the sub arrays - you need to know how many times to loop!
foreach ($_POST['veryfy_doc_type'] as $key => $value) {
// Filter the main array and use the $key (0 or 1) for the callback
$rowValues = array_map(function($row) use ($key) {
// Return the sub-array value using the $key (0 or 1) for this level
return $row[$key];
}, $_POST);
print_r($rowValues);
}
Example: https://eval.in/498895
This would get you structured arrays for each set of data.
From here I'd suggest you leave the arrays as they are rather than exporting to variables, but if you wanted to you you could use the list() as in your example.
You can use a MultipleIterator for that:
<?php
$post = array(
'veryfy_doc_type' => array('1','2'),
'id_number' => array('3242424','4456889'),
'document_issuer' => array(1,3),
'verify_doc_expiry_date' => array('2016-01-26','2015-02-20'),
'doc_id' => array(15,16),
'user_id' => array(14,14)
);
$mit = new MultipleIterator(MultipleIterator::MIT_NEED_ALL|MultipleIterator::MIT_KEYS_ASSOC);
foreach($post as $k=>$v) {
$mit->attachIterator( new ArrayIterator($v), $k);
}
foreach( $mit as $row ) {
echo $row['doc_id'], ' ', $row['id_number'], ' ', $row['verify_doc_expiry_date'], "\r\n";
}
prints
15 3242424 2016-01-26
16 4456889 2015-02-20
If you have control over the client code you can change the names of the POST parameters in a way that php build this structure automagically. E.g.
<form method="POST" action="test.php">
<input type="hidden" name="record[0][veryfy_doc_type]" value="1" />
<input type="hidden" name="record[0][id_number]" value="3242424" />
<input type="hidden" name="record[0][document_issuer]" value="1" />
<input type="hidden" name="record[0][verify_doc_expiry_date]" value="2016-01-26" />
<input type="hidden" name="record[0][doc_id]" value="15" />
<input type="hidden" name="record[0][user_id]" value="14" />
<input type="hidden" name="record[1][veryfy_doc_type]" value="2" />
<input type="hidden" name="record[1][id_number]" value="4456889" />
<input type="hidden" name="record[1][document_issuer]" value="3" />
<input type="hidden" name="record[1][verify_doc_expiry_date]" value="2015-02-20" />
<input type="hidden" name="record[1][doc_id]" value="16" />
<input type="hidden" name="record[1][user_id]" value="14" />
<input type="submit" />
</form>
would do/cause that.
If you only want to get the value of the post then you can have a simple multidimentional loop. no need to make it broad
foreach($_POST as $keyName => $row){
// $keyName will be verify_doc_type, id_number, etc..
foreach($row as $value){
// do something
echo $value;
}
}
Hope that helps.
This method will generate variables of same name as in POST array:
foreach ($_POST as $k => $v )
{
$$k = addslashes(trim($v ));
}
I know this post is a bit old, but I was recently trying to achieve this very same thing.
Hopefully the answer will point others in the right direction.
As per the documentation on list():
Since PHP 7.1, keys can be specified
Example from the manual:
<?php
$arr = ['locality' => 'Tunis', 'postal_code' => '1110'];
list('postal_code' => $zipCode, 'locality' => $locality) = $arr;
echo $zipCode; // will output 1110
echo $locality; // will output Tunis
?>
https://www.php.net/manual/en/function.list.php#121094
I received help already with a previous question about posting an array.
Now I'm trying to add more arrays to the loop
Here's the html
<input class="input stickyinput" type="number" name="pestcount[]">
<input type="hidden" name="cardtype[]" value="<?= htmlspecialchars($obj['cardtype']) ?>" />
<input type="hidden" name="cardid[]" value="<?= htmlspecialchars($obj['card_id']) ?>" />
<input type="hidden" name="pestname[]" value="<?= htmlspecialchars($pestname['scoutlogpestname']) ?>" />
Here's the php
for ($i=0; $i < count($_POST['cardid']); $i++ ) {
$card_id = $_POST['cardid'][$i];
$card_type = $_POST['cardtype'][$i];
$pest_count = $_POST['pestcount'][$i];
$pest_name = $_POST['pestname'][$i];
$sql ="INSERT INTO scout_logpestnum (pest_name,pest_count,card_id,card_type)
VALUES (:pest_name,:pest_count,:card_id,:card_type)";
$q = $pdo->prepare($sql);
$q->execute(array(':pest_name'=>$pest_name,':pest_count'=>$pest_count,':card_id'=>$card_id,':card_type'=>$card_type));
}
So what is the proper format for adding addition arrays from the form?. Thanks;)
Here's what my array looks like.
Array (
[pestcount] => Array (
[0] => 1
[1] => 2
[2] => 3
)
[cardtype] => Array (
[yellcard] =>
)
[cardid] => Array (
[1] =>
)
[pestname] => Array (
[Aphids] =>
[Thrips] =>
[White-Fly] =>
)
Assuming that pests and cards are separate collections, you can simply use a prefix to identify them in $_POST data. For example...
<input name="pests[<?= htmlspecialchars($pestname['scoutlogpestname']) ?>][<?= $obj['card_id'] ?>]" ...
and
<input name="cards[<?= htmlspecialchars($obj['cardtype']) ?>][<?= $obj['card_id'] ?>]" ...
This would produce HTML like
<input name="pests[Aphids][1]" ...
<input name="cards[yellcard][1]" ...
Then, in your form handler...
$pests = $_POST['pests'];
foreach ($pests as $pest_name => $values) {
foreach ($values as $card_id => $pest_count) {
echo $pest_name, $card_id, $pest_count;
}
}
$cards = $_POST['cards'];
foreach ($cards as $card_type => $values) {
foreach ($values as $card_id => $value) {
echo $card_type, $card_id, $value;
}
}
I am trying to create a php array from posted values and then json_encode to achieve this:
[{"network_type":"facebook","network_url":"fb.com/name"},{"network_type":"twitter","network_url":"#name"},{"network_type":"instagram","network_url":"#name"}]
which after json_decode looks like:
array(
[0] => stdClass(
network_type = 'facebook'
network_url = 'fb.com/name'
)
[1] => stdClass(
network_type = 'twitter'
network_url = '#name'
)
[2] => stdClass(
network_type = 'instagram'
network_url = '#name'
)
)
My php looks like this:
$social_data = array(
'network_type' => $this->input->post('network_type'),
'network_url' => $this->input->post('network_url')
);
and so the array is not grouped the way I want it, but rather by the field name:
array(
['network_type'] => array(
[0] => 'facebook'
[1] => 'twitter'
[2] => 'instagram'
)
['network_url'] => array(
[0] => 'fb.com/name'
[1] => '#name'
[2] => '#name'
)
and therefore the result of the json_encode isn't grouped how I want it:
{"network_type":["facebook","twitter","instagram"],"network_url":["fb.com/name","#name","#name"]}
)
So the question is...how do I adjust my php so the array is correct?
--- here's the input fields:
<?php
foreach ($social as $key => $value) {?>
<p>
<label for="network_type"><input type="text" size="20" name="network_type[]" value="<?php echo $value -> network_type; ?>" placeholder="Social Network" /></label>
<label for="network_url"><input type="text" size="20" name="network_url[]" value="<?php echo $value -> network_url; ?>" placeholder="URL or Handle" /></label>
<a class="remNetwork" href="#">Remove</a>
</p>
<?php } ?>
----latest update: this is sooooo close!-----
Ok, for some reason (probably me botching things one way or another), both suggested methods below didn't quite get me there....but, a mix of both methods has gotten me close:
This if/loop/array setup:
$network_type = (array)$this->input->post('network_type', true);
$network_url = (array)$this->input->post('network_url', true);
$social_data = array();
if (($counter = count($network_type)) == count($network_url)){
for($i = 0;$i < $counter; $i++) {
$social_data[$i] = array(
'network_type' => $this->input->post('network_type[$i]'),
'network_url' => $this->input->post('network_url[$i]'),
);
}
}
paired with this input loop:
<?php
foreach ($social as $key => $value) {
?>
<p>
<label for="network_type"><input type="text" size="20" name="network_type[]" value="<?php echo $value -> network_type; ?>" placeholder="Social Network" /></label>
<label for="network_url"><input type="text" size="20" name="network_url[]" value="<?php echo $value -> network_url; ?>" placeholder="URL or Handle" /></label>
<a class="remNetwork" href="#">Remove</a>
</p>
<?php } ?>
is yielding the following:
array(
[0] => array(
['network_type'] => FALSE
['network_url'] => FALSE
)
[1] => array(
['network_type'] => FALSE
['network_url'] => FALSE
)
[2] => array(
['network_type'] => FALSE
['network_url'] => FALSE
)
)
So, I think if I can figure out why these values are false, then we've done it!
Thanks and appreciation for your patience and help in advance...
-- update again ----
To my dismay, I've left out a piece that's perhaps critical...the coffee script that's dynamically creating the form fields when there's more than one social:
$ ->
socialDiv = $("#social")
i = $("#social p").size() + 1
index = 0
$("#addNetwork").click ->
$("<p><label for=\"network_type[]\"><input type=\"text\" id=\"network_type[]\" size=\"20\" name=\"network_type[]\" value=\"\" placeholder=\"Social Network\" /></label><label for=\"network_url[]\"><input type=\"text\" id=\"network_url[]\" size=\"20\" name=\"network_url[]\" value=\"\" placeholder=\"URL or Handle\" /></label> Remove</p>").appendTo socialDiv
i++
false
$(document).on "click", ".remNetwork", ->
#$(".remNetwork").bind "click", ->
if i > 1
$(this).parent("p").remove()
i--
false
In your example, i can asume that network_type and network_url are inputs like:
<input type="text" name="network_type[]" /> and <input type="text" name="network_url[]" />
so in order to accomplish what you want you would:
<?php
$networkType = (array)$this->input->post('network_type', true);
$networkUrl = (array)$this->input->post('network_url', true);
$networkData = array();
if (($counter = count($networkType)) == count($networkUrl)) {
for ($i = 0; $i < $counter; ++$i) {
$networkData[] = array(
'network_type' => $networkType[$i],
'network_url' => $networkUrl[$i]
);
}
}
?>
and should give you the desired json.
However, this approach is a bit clunky and unreliable.
Instead, i would define the input fields like:
<input type="text" name="network[0][network_type]" /> and <input type="text" name="network[0][network_url]" />
<input type="text" name="network[1][network_type]" /> and <input type="text" name="network[1][network_url]" />
and i would generate the php array like:
<?php
$networkData = (array)$this->input->post('network', true);
?>
Just my two cents :)
L.E:
To make it detailed and create the std objects from your array, you would:
$networkData = array();
if (($counter = count($networkType)) == count($networkUrl)) {
for ($i = 0; $i < $counter; ++$i) {
$obj = new StdClass();
$obj->network_type = $networkType[$i];
$obj->network_url = $networkUrl[$i];
$networkData[] = $obj;
}
}
print_r($networkData);
You can use a for loop to iterate through as you feed them into the $social_data array. It would be
for($i = 0;$i < $items.length;$i++) {
$social_data[$i] = array(
'network_type' => $this->input->post('network_type[$i]'),
'network_url' => $this->input->post('network_url[$i]'),
);
The resulting array will look like:
$social_data[0] ->
'network_type' => 'facebook',
'network_url' => 'fbook.com/user'
$social_data[1] ->
...etc
I'm not totally sure what context you're getting the network_type and url but they will both be arrays and looping through for each individual value is what to do. Without the rest of the code it's hard to get much more specific but hopefully this will point you in the right direction.
I have multiple items with name module_name, and each of them have multiple input fields. Please see below:
<input type="hidden" value="slideshow" name="module_name[]">
<input type="hidden" value="" name="slide_title[]">
<input type="hidden" value="" name="slide_info[]">
<input type="hidden" value="" name="slide_title[]">
<input type="hidden" value="" name="slide_info[]">
I want to get all data when it is posted, so I'm trying this:
if(isset($_POST['module_name'])){
foreach ($_POST['module_name'] as $k => $v) {
foreach ($_POST['slide_title'] as $key => $value) {
$slide_title = addslashes($_POST['slide_title'][$key]);
$slide_info = addslashes($_POST['slide_info'][$key]);
$arr[] = array(
'slide_title' => $slide_title,
'slide_info' => $slide_info,
);
}
}
print_r($arr); //incorrect data
}
I want to get data of each module_name in an array, but with the above code I do not get correct data in the array, it displays the repeating data.
If you have more than one slide_title and slide_info for one module_name i think you have to change your structure:
<input type="hidden" value="slideshow" name="module_name[1]">
<input type="hidden" value="" name="slide_title[1][]">
<input type="hidden" value="" name="slide_info[1][]">
<input type="hidden" value="" name="slide_title[1][]">
<input type="hidden" value="" name="slide_info[1][]">
...
<input type="hidden" value="slideshow" name="module_name[2]">
<input type="hidden" value="" name="slide_title[2][]">
<input type="hidden" value="" name="slide_info[2][]">
<input type="hidden" value="" name="slide_title[2][]">
<input type="hidden" value="" name="slide_info[2][]">
So with this structure you can loop through your data like this:
$arr = array();
foreach($_POST['module_name'] as $key => $value) {
$data = array();
foreach($i = 0; $i < count($_POST['slide_title'][$key]); $i++) {
$data[] = array(
"slide_title" => $_POST['slide_title'][$key][$i],
"slide_info" => $_POST['slide_info'][$key][$i]
);
}
$arr[$value] = $data;
}
An result would look like this:
"module_name_1" => array(
array("slide_title" => "slide_title_1", "slide_info" => $slide_info_1),
array("slide_title" => "slide_title_2", "slide_info" => $slide_info_2),
array("slide_title" => "slide_title_3", "slide_info" => $slide_info_3)
),
"module_name_2" => array(
array("slide_title" => "slide_title_1", "slide_info" => $slide_info_1),
array("slide_title" => "slide_title_2", "slide_info" => $slide_info_2),
array("slide_title" => "slide_title_3", "slide_info" => $slide_info_3)
)
...
You should notice, that this loop expect the same amount of slide_title and slide_info fields for each module_name.
I hope this is the desired result.
Pay attention to the options array this array holds an array of properties on the database, there is a call for the database in the script it's not nessecary to add here, it retrieves the data because it's already on there...
$meta_boxes[] = array(
'id' => 'page_metabox',
'fields' => array(
array(
'name' => ''.$slider['properties']['title'].'',
'desc' => 'Upload an image/pattern for the static area.',
'id' => $prefix . 'text_BOMB',
'type' => 'sortable',
'options' => $slider['properties'],
'multiple' => true,
),
);
The data HTML is outputted using a foreach and an input...
<?php foreach ( $field['options'] as $value => $name ) : ?>
<input type="text" name="<?php echo $field['id'].'[]' ?>" id="<?php echo $field['id'] ?>" value="<?php echo $value; ?>" />
<?php endforeach; ?>
This is exactally what I want, I have a list of inputs for each property... then it hit me, what if its a new user and the data isnt on their database yet the foreach wont output anything and then there is no way to write it to the database... this is pretty noobish but that means an easier answer for you guys :p
You could use empty - function:
<?php
if (empty($field['options'])) {
//do something when options are empty
}
else { //the array $field['options'] has something in it
foreach ( $field['options'] as $value => $name ) : ?>
<input type="text" name="<?php echo $field['id'].'[]' ?>" id="<?php echo $field['id'] ?>" value="<?php echo $value; ?>" />
<?php endforeach;
}
?>