Get form serialize value from the array list - php

I have an array like this:
Array
(
[action_name] => edit
[formData] => color=red&size=full&symmetry=square&symmetry=circle&symmetry=oval
)
Here, form data is coming using the serialize method of JS and so it is displayed like above. I want to get each data from the formData key. How can I get that?
I tried:
$_POST['formData']['color']
But that is not working. I think the method to fetch this shall be different. How can I do that?

You can use parse_​str to "parse string as if it were the query string passed via a URL and sets variables in the current scope (or in the array if result is provided)."
<?php
$_POST = [
'action_name' => 'edit',
'formData' => 'color=red&size=full&symmetry=square',
];
parse_str($_POST['formData'], $parsed);
print_r($parsed);
will output
Array
(
[color] => red
[size] => full
[symmetry] => square
)
Edit:
Having multiple values for symmetry, your query should look like:
<?php
$_POST = [
'action_name' => 'edit',
'formData' => 'color=red&size=full&symmetry[]=square&symmetry[]=circle&symmetry[]=oval',
];
parse_str($_POST['formData'], $parsed);
print_r($parsed);
This would output:
Array
(
[color] => red
[size] => full
[symmetry] => Array
(
[0] => square
[1] => circle
[2] => oval
)
)

Related

Convert a json to multi-dimensional PHP array

I have the following json sent to my API endpoint
{"key":"levels","value":"[{role_id:1, access_level_id:3}, {role_id:2, access_level_id:1}, {role_id:3, access_level_id:2}]","description":""}
at the backend, I receive it as a Laravel request as follows:
public function functionName(Request $request){
$req=$request->all();
Log::debug($req['value']);
return;
}
And it returns the following expected result
array (
'key' => 'levels',
'value' => '[{role_id:1, access_level_id:3}, {role_id:2, access_level_id:1}, {role_id:3, access_level_id:2}]',
'description' => NULL,
)
But I need to convert the 'value' to array also. so that I can have a multidimensional PHP array. So I expect to get something like
array (
'key' => 'levels',
'value' => array(
array('role_id'=>1, 'access_level_id'=>3),
array('role_id'=>2, 'access_level_id'=>1),
array('role_id'=>3, 'access_level_id'=>2)
)
'description' => NULL,
)
but when in my Laravel method I do the following:
public function share_doc(Request $request){
$req=$request->all();
Log::debug(json_decode($req['value'],true));
return;
}
trying to convert the json received as 'value' to PHP array, it returns nothing -i.e. no value, no array, no string. Just nothing.
So, my struggle here is how I can convert the entire json string received as 'value' from the request to a PHP array so that I can iterate through the items with PHP
Thank you for helping
Your problem is that the value element is not valid JSON as the keys are not quoted. For the sample data you provide, you can fix that with preg_replace and then json_decode the changed value:
$x['value'] = json_decode(preg_replace('/(\w+)(?=:)/', '"$1"', $x['value']), true);
print_r($x);
Output:
Array
(
[key] => levels
[value] => Array
(
[0] => Array
(
[role_id] => 1
[access_level_id] => 3
)
[1] => Array
(
[role_id] => 2
[access_level_id] => 1
)
[2] => Array
(
[role_id] => 3
[access_level_id] => 2
)
)
[description] =>
)
Demo on 3v4l.org

PHP - How to properly merge 2 arrays multi level in this example?

I have the follow array:
$arrIni["ENV"]="US";
$arrIni["sap_db_server"] = "192.xxx.x.xx";
$arrIni["local_db_server"] = "localhost";
$arrIni["local_db_username"] = "root";
//Default settings
$arrIni["arrEnvSettings"]["UserTypeID"]=4;
$arrIni["arrEnvSettings"]["LocalizationID"]=1;
$arrIni["arrEnvSettings"]["LangLabels"] = array();
$arrIni["arrEnvSettings"]["pages"]["st1"]="st1.php";
$arrIni["arrEnvSettings"]["pages"]["st2"]="st2.php";
$arrIni["arrEnvSettings"]["pages"]["st3"]="st3.php";
And I want to merge with this one:
$setParam["arrEnvSettings"]["pages"]["st3"]="st3_V2.php";
This is what I am doing:
echo "<pre>";
print_r(array_merge($arrIni,$setParam));
echo "</pre>";
And this is what I am getting:
Array
(
[ENV] => US
[sap_db_server] => 192.xxx.x.xx
[local_db_server] => localhost
[local_db_username] => root
[arrEnvSettings] => Array
(
[pages] => Array
(
[st3] => st3_V2.php
)
)
)
In the php doc about merge, this is the comment " ...If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. ..."
So in this way, I suppose to get this output instead of the last one:
Array
(
[ENV] => US
[sap_db_server] => 192.xxx.x.xx
[local_db_server] => localhost
[local_db_username] => root
[arrEnvSettings] => Array
(
[UserTypeID] => 4
[LocalizationID] => 1
[LangLabels] => Array
(
)
[pages] => Array
(
[st1] => st1.php
[st2] => st2.php
[st3] => st3_V2.php
)
)
)
I do not understand why $setParam["arrEnvSettings"]["pages"]["st3"] is overriding the entire $arrIni["arrEnvSettings"].
Note:
If I use array_merge_recursive($arrIni,$setParam)) I will have the follow result but it is not what I want.
Array
(
[ENV] => US
[sap_db_server] => 192.xxx.x.xx
[local_db_server] => localhost
[local_db_username] => root
[arrEnvSettings] => Array
(
[UserTypeID] => 4
[LocalizationID] => 1
[LangLabels] => Array
(
)
[pages] => Array
(
[st1] => st1.php
[st2] => st2.php
[st3] => Array
(
[0] => st3.php
[1] => st3_V2.php
)
)
)
)
Is there a way to do this without iterate over the array? Only using merging? What am I doing wrong?
This should do the trick:
array_replace_recursive($arrIni,$setParam);
If you want to merge a given value, use this:
$arrIni["arrEnvSettings"]["pages"]["st3"] = $setParam["arrEnvSettings"]["pages"]["st3"];
But the way you're doing it is merging two arrays, not simply setting the value within an array. There's a gigantic difference between those two methods.
Otherwise, yes you will need to iteratively merge the arrays.
what you need is array_replace_recursive
print_r(array_replace_recursive($arrIni,$setParam));
didnt see the submitted answer..Felippe Duarte has given it already.....

print_r blank space in output

I'm working with arrays in PHP and I have noticed strange output with some of the values having an extra line of blank space as shown below.
Array
(
[0] => Array
(
[token] => data
[tag] => data
)
[1] => Array
(
[token] => data
[tag] => data
)
etc.
This alternates with every other element having the extra blank space until element 5. Then they all look like [1] until they reach element [9] which has the strange whitespace line again.
Some data is duplicate too yet this doesn't effect whether the two elements will have the same whitespace issue.
Can this cause me problems or does it show an issue within my code? Why do some elements have this additional whitespace?
EDIT:
I did a var dump, and I have identified that some of the tags have a newline after them.
e.g.
"tagexample
"
rather than
"tagexample"
This is confusing however because as I said, a lot of the tags are duplicates and used for multiple tokens and it seems random which is affected.
EDIT2:
I did var export and that shows the same result as above, i.e.
'tag' => 'data
',
try this:
$arr = array(
array( 'token' => 'stuff 1',
'tag' => 'data 1
', ),
array( 'token' => 'stuff 2',
'tag' => 'data 2
', ),
array( 'token' => 'stuff 3',
'tag' => 'data 3
', ),
);
print "<pre>";
print_r($arr);
foreach($arr as $index => $sub) {
$arr[$index] = array_map('trim',$sub);
}
print "\n\n----------------------------------------------------\n\n";
print_r($arr);
/*
Array
(
[0] => Array
(
[token] => stuff 1
[tag] => data 1
)
[1] => Array
(
[token] => stuff 2
[tag] => data 2
)
[2] => Array
(
[token] => stuff 3
[tag] => data 3
)
)
----------------------------------------------------
Array
(
[0] => Array
(
[token] => stuff 1
[tag] => data 1
)
[1] => Array
(
[token] => stuff 2
[tag] => data 2
)
[2] => Array
(
[token] => stuff 3
[tag] => data 3
)
)
*/
could also be written as:
function trim_the_sub_array($sub) {
return array_map('trim',$sub);
}
$arr = array_map('trim_the_sub_array',$arr);
print_r() is a debugging function (http://php.net/print_r) and you need not worry about the whitespaces if you are using it for debugging. If you use it for output (say for a log), var_export() (http://php.net/var_export) would be a better choice since it prints actual PHP code for defining the array in question.
As you have mentioned, if some data is duplicated and if it's not the intended behavior then probably there is an issue in your code. You will be able figure that out by focusing on where the array is populated.

jQuery post input with same names but in different arrays

I have various forms in a single page.
All the forms get submitted by the below jQuery function.
All is ok, but there is a specific form that has duplicated input names.
In fact in this form the inputs get cloned on request.
So for example, this form represents how many people attend an event.
The user can add as many people as he wants and adding details of each by filling the form.
The inputs get cloned on the fly and inserted inside the form.
The problem is that jQuery is sending them in the wrong way, like shown below, and my php code is not responding well. In fact it just sees one of the posted "people" instead that them all.
Example of jquery post:
protagonist_description zxcvvcbhcvbjfg
protagonist_description jfghjfghjh
protagonist_email
protagonist_email
protagonist_name zxcvzxcv
protagonist_name dfghdfgh
protagonist_phone
protagonist_phone
protagonist_role zxcvxzcv
protagonist_role hgfjgfhjhgh
protagonist_surname zcxvzxcv
protagonist_surname dfghd
protagonist_video
protagonist_video
protagonist_website
protagonist_website
Example of PHP response:
Array
(
[protagonist_name] => dfghdfgh
[protagonist_surname] => dfghd
[protagonist_role] => hgfjgfhjhgh
[protagonist_description] => jfghjfghjh
[protagonist_email] =>
[protagonist_phone] =>
[protagonist_website] =>
[protagonist_video] =>
)
As you see it just gets the last posted.
Here is my jQuery function:
$(".save").click(function() {
$.ajax({
type: 'POST',
data: $('form[name="wizard_form"]').serialize(),
success: function() {
$('#publish').modal('show');
}
});
});
Please note that all the cloned inputs are inside the same form.
I can only use one form. So please do not suggest using more cloned forms. It won't work for my code as it is.
I am looking for a way to correctly merge the inputs with the same name in specific arrays posted to the PHP code.
How to do that?
You first need to change your form inputs to be arrays by adding [] to the name like so:
<input name="protagonist_description[]" />
And then in your PHP it will look like this:
Array
(
[protagonist_name] => Array
(
[0] => zxcvzxcv,
[1] => dfghdfgh,
)
[protagonist_surname] => Array
(
[0] => zcxvzxcv,
[1] => dfghd,
)
[protagonist_role] => Array
(
[0] => zxcvxzcv,
[1] => hgfjgfhjhgh,
)
[protagonist_description] => Array
(
[0] => zxcvvcbhcvbjfg,
[1] => jfghjfghjh,
)
[protagonist_email] => Array
(
[0] => ,
[1] => ,
)
[protagonist_phone] => Array
(
[0] => ,
[1] => ,
)
[protagonist_website] => Array
(
[0] => ,
[1] => ,
)
[protagonist_video] => Array
(
[0] => ,
[1] => ,
)
)
At this point you can then loop through the values like this:
for ($i = 0, $max = count($_POST['protagonist_name']); $i < $max; $i++) {
$first_protagonist = array(
'protagonist_name' => $_POST['protagonist_name'][$i],
'protagonist_surname' => $_POST['protagonist_surname'][$i],
// ...
);
}
Per David's suggestion, here's the code for a foreach if you wish:
foreach ($_POST['protagonist_name'] as $key => $val) {
$first_protagonist = array(
'protagonist_name' => $val,
'protagonist_surname' => $_POST['protagonist_surname'][$key],
'protagonist_description' => $_POST['protagonist_description'][$key],
// ...
);
}
You need to add brackets to your input's name.
Example:
<input name="my_name[]" value="david" />
<input name="my_name[]" value="john" />
<input name="my_name[]" value="francis" />
$_POST['my_name'] will be an array containing all results.
Array
(
[my_name] => Array
(
[0] => david
[1] => john
[2] => francis
)
)
To handle arrays of input elements, in other words defined as having the same element name. If you define the name with two square brackets in the end it will be transformed to an array on the server side for php.
<input type='text' name='elmname[]' .....
<input type='text' name='elmname[]' .....
if you submit the form consisting these elements and then on the php side you will see that $_POST['elmname'] will be an array

How can i create a array with double GET variables

i have a form with some checkboxes. if i activate a ceckbox, jquery is sending the data with the .serialize() function to a php file via ajax. The problem is, that jquery send some double parameters. Here is the Query:
area=26-50&area=51-75&area=76-100&area=100&std=1&std=3
How can i create a array like this:
array(
'area' => array(0 => '26-50',1 => '51-75',2 => '76-100'), std => array(0 => 1,1 => 3)
)
PHP overwrites the last variable with a new one...
Thanks for the help!
greetings
[] notation will make it possible to transmit array data in a form.
Name the checkboxes in the form like this:
<input name="area[]" type="checkbox" value="51-75">
this should build an array of all selected check boxes.
PHP can support this if the key name is appended with []:
area[]=26-50&area[]=51-75&area[]=76-100&area[]=100&std[]=1&std[]=3
/*
Array
(
[area] => Array
(
[0] => 26-50
[1] => 51-75
[2] => 76-100
[3] => 100
)
[std] => Array
(
[0] => 1
[1] => 3
)
)
*/

Categories