Group select boxes into array for post? - php

I know how to send data via a multi-select form object and group the data into an array:
<select name="my_data[]" multiple="multiple"/>
Is it possible to have multiple different select boxes with "single" values and push them all into an array? i.e.
<select id="select-1" name="my_data[]"/>
<select id="select-2" name="my_data[]"/>
result would be
[
0 => {value of select-1},
1 => {value of select-2}
]
What would be a good way to combine the data from the selects into an array if not possible?

Ah, just removing multiple seems to work. Zend Framework's FormSelect helper automatically added it when you have "[]" in your form element name and I did not realize that.

This assume you're getting all <select>'s on the page:
// get all selects
var boxes = document.getElementsByTagName("select"),
arr = []; // your final values array
// for each select, pull out the value and push it into 'arr'
for(var i = 0, len = boxes.length; i < len, i++) {
arr.push(boxes[i].value);
}

While you probably can do it I wouldn't recommend it. Just because it isn't that clear from someone else reading the code.
A better approach is simply to combine them serverside. Assuming:
<select id="select-1" name="data_1[]"/>
...
<select id="select-2" name="data_2[]"/>
...
On the PHP side:
$data1 = $_POST['data_1'];
$data2 = $_POST['data_2'];
$combined = array_merge($data1, $data2);

Related

Nested foreach not filling my dropdown correctly

I'm attempting to make 1 array out of 2 existing arrays (which cannot be modified). In order to do this I'm creating the array in a foreach which is nested in another foreach.
The code I used:
$language_option = array();
foreach(Languages::getFullSelectOptionsList() as $country_description_1 => $country_code){
foreach(Languages::getFullSelectOptionsList(TRUE) as $country_description_2 => $country_code){
$language_option[$country_code] = $country_description_1.' - '.$country_description_2;
}
}
In this code "Languages::getFullSelectOptionsList()" returns an array with the 1st country descriptions.
And "Languages::getFullSelectOptionsList(TRUE)" returns an array with the 2nd country descriptions.
This is what my code does:
dropdown results
But what I'd like it to do is:
dropdown wished results
As you can see in the first picture only the last array value of "country_description_1" is used instead of using them all.
Are there any errors in my code, is this not possible to do or is there an easier way of doing this?
Thanks.
Here you can get reference of this code.
But This will not work because you need to specify the values where $first_array[$i]
$language_option = array();
$first_array = Languages::getFullSelectOptionsList();
$second_array = Languages::getFullSelectOptionsList(TRUE);
for($i=0;$i<count($first_array); $i++){
$language_option[$country_code] = $first_array[$i].' - '.$second_array[$i];
}
Instead of $first_array[$i].' - '.$second_array[$i] put code according to your array structure to get description or code (key value).

PHP - Get input from dynamically added html table rows

I have the following Fiddle set up here Fiddle
As you can see, I am able to add inputs by clicking the Add Row button.
All inputs that are added have a unique id and name. The problem is, I cant just do something like
$actionInput = $_POST["actionInput"];
Because I might need
$actionInput1 = $_POST["actionInput1"];
$actionInput2 = $_POST["actionInput2"];
$actionInput3 = $_POST["actionInput3"];
Depending on how many rows are added. So how can I get all the inputs without knowing what inputs I need to grab?
Thanks
Actually, you need to maintain counter in hidden, which you will get at the time of posting the form in case you don't want to maintain elements as array, otherwise you can put elements as array as described below:
<input type=text name="inputs[]" />
Name your inputs with array boundary, like:
<input type=text name="actioninput[]" />
now you can itreate throught them in you POST or GET ( depends ) array:
print_r($_POST);
Assuming your JSFiddle works fine for you, following are the steps.
1) Get keys of $_POST.
2) Get maximum counter value from keys.
3) Take a for loop from 0 to count of post.
4) If counter is 0, no suffix, else, add counter as suffix.
5) Now, you get posted variable.
6) Repeat it for every element in rows.
<?php
$keys = array_keys($_POST);
$keys = implode(',', $keys);
$n = str_replace('actionInput', '', $keys);
$m = explode(',', $n);
$max = max($m);
for ($i=0 ; $i<=$max ; $i++) {
$suffix = ($i==0) ? '' : $i;
if (isset($_POST['actionInput' . $suffix])) {
echo "<br/>-".$_POST['actionInput' . $suffix];
}
}
replace name=actionInput with name=actionInput[]
it should be an array with same name
same thing will apply with all form fields generated dynamically whose values you'll need.
Change this line in Add row jquery event
return name + i to return name
Remove i from it and then
name=actionInput[]
print_r($_POST);
It will gives array of actioninput

javascript equivalent to php max for arrays

I have a function in php that selects the array with that contains the most elements.
$firstArray = array('firstArray','blah','blah','blah');
$secondArray = array('secondArray','blah','blah');
$thirdArray = array('thirdArray','blah','blah','blah','blah');
then I get the name of the variable with the highest length like this:
$highest = max($firstArray, $secondArray, $thirdArray)[0];
but I am developing an application and I want to avoid using php and I have tried javascript's Math.max() to achieve the same results but it doesn't work the same way unless I do
Math.max(firstArray.length, secondArray.length, thirdArray.length)
But this is useless since I need to know the name of the array that contains the most elements. Is there any other way to achieve this?
This function takes as input an array of arrays, and returns the largest one.
function largestArray(arrays){
var largest;
for(var i = 0; i < arrays.length; i++){
if(!largest || arrays[i].length > largest.length){
largest = arrays[i];
}
}
return largest;
}
We can test it out with your example:
firstArray = ['firstArray','blah','blah','blah'];
secondArray = ['secondArray','blah','blah'];
thirdArray = ['thirdArray','blah','blah','blah','blah'];
// should print the third array
console.log(largestArray([firstArray, secondArray, thirdArray]));
The following url has a max() equivalent. It supports more then just numbers just like in php:
js max equivalent of php
If you feel ok with including 3rd-party libs, maybe http://underscorejs.org/#max does what you want:
var aList = [firstArray, secondArray, thirdArray];
_.max(aList, function(each) { return each.length; });

Php javascript conflict with passing javascript to php

I have a slight problem. I have several arrays in php with different team names. Each array contains teams of a certain league. When I click an add button I get the option to add a new entry to the calendar. I want the drop down to have only the teams for that league. onclick of the add button I call a javascript function that knows what division was clicked. However in order to give the javascript the information for which teams to display I have to pass it one of the php arrays. The problem I am having is telling php which array to pass to javascript depending on which league javascript is on. I don't want to specify the array myself because there is an option to add a league and this would mean having to code in more code each time a league is added. The point of the site is being dynamic.
here is some code.
for ($i = 0;$i<$sizeof($leaguesarray);$i++){
$htmlimploded[$i] = implode($html[$i]);
}
here I have used emplode to make all of my php arrays readable into javascript.
for (var h = 0; h<size; h++){ // goes through every league
if(h == leaguenum){ // finds the league for the clicked add button
// this is the line that I have trouble with I can't think of
//anyway of telling it which array to use since it is serverside code.
var myarray = ["<? echo $htmlimploded[]?>"];
}
}
Javascript code above.
Imploding works but why not json_encode($array)? It's a simpler, built in way to turn php arrays into javascript objects or arrays. If you have something like:
$league1 = array('team1', 'team2');
$league2 = array('team3, 'team4') ;
Then make a multidimensional associative array of these:
$all_teams = array('league1'=>$league1, 'league2'=>$league2);
encode it into a Javascript object and print it into your JS:
$encoded = json_encode($all_teams);
print 'var teamObject = '.$encoded.';';
If you were to console.log(teamObject) you'd see something like this:
{"league1": ["team1", "team2"], "league2": ["team3", "team4"]}
Looks complicated, but now you can pull out the array you desire very easily. The league 1 array is teamObject.league1 and the league2 array is teamObject.league2, and so on.
i think you missed something in the following code:
var myarray = ["<? echo $htmlimploded[]?>"];
By right, it should be:
var myarray = ["<?php echo $htmlimploded[]?>"];
Assuming that PHP knows the names of the leagues and the teams and that JavaScript knows the league name that is clicked, You can wrap the arrays of the team names inside an object with the league as the name of the property.
<?php
$arr = array("League1" => array("Team 1", "Team 2"),
"League2" => array("Team 3", "Team 4")
);
?>
var obj = {};
<?php foreach ($arr as $k => $v): ?>
obj.<?php echo $k; ?> = ["<?php echo implode('","', $v); ?>"];
<?php endforeach; ?>
Then when a user selects a league, you can loop through the array of the property (which is the league name) of the object.
clickedLeague = "League1";
for (var i = 0; i < obj[clickedLeague].length; i++)
{
console.log(obj[clickedLeague][i]); // Logs the team name to console
}

How to process a large post array in PHP where item names are all different and not known in advance?

I have a PHP page that queries a DB to populate a form for the user to modify the data and submit.
The query returns a number of rows which contain 3 items:
ImageID
ImageName
ImageDescription
The PHP page titles each box in the form with a generic name and appends the ImageID to it. Ie:
ImageID_03
ImageName_34
ImageDescription_22
As it's unknown which images are going to have been retrieved from the DB then I can't know in advance what the name of the form entries will be.
The form deals with a large number of entries at the same time.
My backend PHP form processor that gets the data just sees it as one big array:
[imageid_2] => 2
[imagename_2] => _MG_0214
[imageid_10] => 10
[imagename_10] => _MG_0419
[imageid_39] => 39
[imagename_39] => _MG_0420
[imageid_22] => 22
[imagename_22] => Curly Fern
[imagedescription_2] => Wibble
[imagedescription_10] => Wobble
[imagedescription_39] => Fred
[imagedescription_22] => Sally
I've tried to do an array walk on it to split it into 3 arrays which set places but am stuck:
// define empty arrays
$imageidarray = array();
$imagenamearray = array();
$imagedescriptionarray = array();
// our function to call when we walk through the posted items array
function assignvars($entry, $key)
{
if (preg_match("/imageid/i", $key)) {
array_push($imageidarray, $entry);
} elseif (preg_match("/imagename/i", $key)) {
// echo " ImageName: $entry";
} elseif (preg_match("/imagedescription/i", $key)) {
// echo " ImageDescription: $entry";
}
}
array_walk($_POST, 'assignvars');
This fails with the error:
array_push(): First argument should be an array in...
Am I approaching this wrong?
Would it be possible to change the way the items are named on the form?
Current:
ImageID_03
ImageName_34
ImageDescription_22
Changed To:
ImageID[03]
ImageName[34]
ImageDescription[22]
This way it should come through the $_POST as three separate arrays meaning you can skip all that extra processing.
I hate to edit many rows at once. It's usability fault
If I go for it, I'd make it with such a form:
<form method="POST">
<input type="text" name="name[1]">
<input type="text" name="desc[1]">
<input type="text" name="name[2]">
<input type="text" name="desc[2]">
...etc
</form>
So, I'd have 2 arrays, $_POST['name'] and $_POST['desc'] where id used as a key
In your case I wouldn't use array_walk as it's just a syntax sugar, and make it with foreach to have full contorol over data processing.
I think you need
global $imageidarray;
to access a global array inside a function.
Something like this would work as well, assuming your three form fields are always submitted together:
$ids = preg_grep('/^imageid_(\d+)$/', array_keys($_POST)); // $ids now contains only the imageid_* keys
foreach($ids as $id) {
$id = substr($ids, 8); // now contains the numeric id of the field
echo $id, ": ", $_POST["imageid_$id"], "\n";
}
Not as efficient as using the array notation in the form names, but allows you to trivially extract just the ID numbers from one of the field names and then use it to access the other matching fields as well.

Categories