convert POST array data to json format - php

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

Related

How to get key of dynamic created input fields in 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);
}

Generate array with for loop

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

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 to edit collection fields (ZF2) on the fly with jQuery

I have a Collection created with ZF2. The HTML code looks for eg as follows:
<fieldset id="benutzer">
<legend>Team</legend>
<div class="controls-row">
<span data-template="<input type="hidden" name="projekt[benutzer][__placeholder__][benutzerid]" class="benutzerid" value=""><input name="projekt[benutzer][__placeholder__][benutzername]" class="benutzername" title="Kollege" placeholder="Name" type="text" value=""><input type="hidden" name="projekt[benutzer][__placeholder__][bearbeiten]" value="0"><input type="checkbox" name="projekt[benutzer][__placeholder__][bearbeiten]" title="Bearbeiten" class="bearbeiten" value="1"><input name="projekt[benutzer][__placeholder__][bemerkung]" title="Bemerkung" placeholder="Bemerkung" type="text" value="">"></span>
<input type="hidden" value="4" class="benutzerid" name="todo[benutzer][0][benutzerid]">
<input type="text" value="Julian" placeholder="Name" title="Kollege" class="benutzername" name="todo[benutzer][0][benutzername]">
<input type="hidden" value="0" name="todo[benutzer][0][bearbeiten]">
<input class="bearbeiten" type="checkbox" checked="checked" value="1" title="Bearbeiten" name="todo[benutzer][0][bearbeiten]">
<input type="text" value="" placeholder="Bemerkung" title="Bemerkung" name="todo[benutzer][0][bemerkung]">
<div>
<div class="row">
<input type="hidden" value="5428" class="benutzerid" name="todo[benutzer][0][benutzerid]">
<input type="text" value="Hans" placeholder="Name" title="Kollege" class="benutzername" name="todo[benutzer][0][benutzername]">
<input type="hidden" value="0" name="todo[benutzer][0][bearbeiten]">
<input class="bearbeiten" type="checkbox" checked="checked" value="1" title="Bearbeiten" name="todo[benutzer][0][bearbeiten]">
<input type="text" value="" placeholder="Bemerkung" title="Bemerkung" name="todo[benutzer][0][bemerkung]">
<div>
</fieldset>
The user should now be able to check/uncheck the checkboxes, edit the input fields but also delete and/or add rows. The collections of ZF2 need the indexes of its rows to start at 0 and count up each row by 1. This means, if I delete a row and the row was not adventitiously at the end of the collection, I have to correct the indexes. I am trying to do this with jQuery.
And here is my Porblem: If I changed anything before I re-sort the rows (and I do this in the end everytime before I submit the form), the changes are not preserved. If I check a checkbox, if I enter something to the "Bemerkung"-field, everything will be discarded.
Here is my code:
Add a new row:
function add_category( $collectionType ) {
// Create and append new row
var $template = $('#'+$collectionType+' span').data('template');
var $currentCount = $('#'+$collectionType+' .'+$collectionType+'id').length;
$template = $template.replace(/__placeholder__/g, String($currentCount));
$newrow = "<div class=\"controls-row new-row\">"+$template+"<div class=\"span1\"><i class=\"icon-remove\"></i></div></div>";
$('#'+$collectionType).append($newrow);
return false;
}
Re-sort the collection:
$.fn.resortCollection = function (){ // execute with Collection-Fieldset!
$c = 0;
$fieldset = $(this);
// re-sort the rows, indexes
$.each( $fieldset.find('.controls-row'), function(){
$html = $(this).html();
$newhtml = $html.replace(/\[\d+\]/g, '['+$c+']');
$(this).html($newhtml);
$c++;
});
};
Delete a row in the collection:
$.fn.deleteRow = function (){
var $row = this.closest('div.controls-row');
var $fieldset = $row.closest('fieldset');
$($row).remove();
$fieldset.resortCollection();
};
How can I access the current state of the DOM including my changes while re-sorting the rows?
Actually Zend\Form\Element\Collection preserves the keys of a collection. The only problem that i found is that if you initially define collection with the option count > 0 e.g.:
$this->add(array(
'type' => 'Zend\Form\Element\Collection',
'name' => 'data',
'options' => array(
'count' => 2,
'allow_add' => true,
)
));
it will always add as much missing elements at the begining of the collection as you defined with count option. From the example above it will add elements with indexes 0 and 1 if they are missing in the collection.
I fixed that by extending Zend\Form\Element\Collection and rewriting one method:
namespace MyNamespace;
use Zend\Form\Element\Collection as ZendCollection;
use Zend\Form\Exception;
use Traversable;
class MyCollection extends ZendCollection
{
public function populateValues($data)
{
if (!is_array($data) && !$data instanceof Traversable) {
throw new Exception\InvalidArgumentException(sprintf(
'%s expects an array or Traversable set of data; received "%s"',
__METHOD__,
(is_object($data) ? get_class($data) : gettype($data))
));
}
if (sizeof($data)){
foreach ($this->byName as $name => $element) {
if (!isset($data[$name])) {
$this->remove($name);
}
}
}
parent::populateValues($data);
}
}
Hope it will help you to simplify your code.

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