Pass array values into select option fields within a form? - php

This is based in PHP.
Is it possible to take an array like this:
$SELECT_INDUSTRY = array("Medical" => "Specialty", "Dental" => "Specialty", "Pediatrics" => "Specialty");
And have that pass those two values into something simple like this:
<select>
<option value="$SELECT_INDUSTRY[]">$SELECT_INDUSTRY[]</option>
</select>
Where Medical would be the value being passed, and Specialty would be the public facing text.
This is the function I'm using to build the actual select boxes:
$SELECT_INDUSTRY = array("Medical", "Dental", "Pediatrics");
$FORM_SELECT_SIZE = 'input-min';
function get_options_industry( $arr = array() ) {
global $FORM_SELECT_SIZE;
echo '<div class="control-group"><label class="control-label" for="industry">Industry</label><div class="controls"><select name="industry" id="industry" class="'.$FORM_SELECT_SIZE.'"><option value=>Select an Industry</option>';
foreach( $arr as $option ) {
echo '<option>'.$option.'</option>';
}
echo '</select></div></div>';
}
$FORM_FIELD_INDUSTRY = $SELECT_INDUSTRY;
And this is how I'm displaying the select:
<?php get_options_industry( $FORM_FIELD_INDUSTRY ) ?>
I feel like I'm close, or at least on the right track, just can't figure out how to pull the first array value into the value field, then the second into the actual name.
The goal is to get the value being passed in the form, is different than the public facing name. I realize that the above array definition I gave may not be the correct way to do this.
SOLUTION
Thanks to a couple responses below, here is the final answer to solve my problem:
$SELECT_INDUSTRY = array("Medical" => "Medical", "Dental" => "Medical", "Pediatrics" => "Medical");
$FORM_SELECT_SIZE = 'input-min';
function get_options_industry( $arr = array() ) {
global $FORM_SELECT_SIZE;
echo '<div class="control-group"><label class="control-label" for="industry">Industry</label><div class="controls"><select name="industry" id="industry" class="'.$FORM_SELECT_SIZE.'"><option value=>Select an Industry</option>';
foreach( $arr as $key => $value ) {
echo '<option value="'.$value.'">'.$key.'</option>';
}
echo '</select></div></div>';
}
$FORM_FIELD_INDUSTRY = $SELECT_INDUSTRY;
I then have to make sure that my key is unique so no duplicates are erased.

How about this?
$SELECT_INDUSTRY = array("Medical" => "Specialty", "Dental" => "Specialty", "Pediatrics" => "Specialty");
.... other stuff you already have ....
foreach( $arr as $val => $option ) {
echo '<option value="'.$val.'">'.$option.'</option>';
}

Quick example...
$SELECT_INDUSTRY = array("Medical" => "Specialty", "Dental" => "Specialty", "Pediatrics" => "Specialty");
echo '<select>';
foreach ($SELECT_INDUSTRY as $key => $value) {
echo '<option value="' . $value . '">' . $key . '</option>';
}
echo '</select>';
You can reverse $key and $value depending on which you want displayed as the text and which you would like passed as the value. The way I displayed it in my example made the most sense to me.

This one works fine
$SELECT_INDUSTRY = array("Medical", "Specialty", "Dental", "Specialty", "Pediatrics", "Specialty");
echo '<select>';
foreach ($SELECT_INDUSTRY as $key => $value) {
echo '<option value="' . $value . '">' . $key . '</option>';
}
echo '</select>';

Related

The UTF-8 sorted array doesn't work with foreach in PHP

Only the collator (UTF-8 sorted array) works without foreach and with only one value in an array.
But I am using foreach and multiple values in an array.
Here is the code:
<select name="courses">
<?php
$list_courses =
array(
array("course" => "Management",
"value" => "course1",
"emoji" => "test1"),
array("course" => "Éducation Physique",
"value" => "course2",
"emoji" => "test2"),
array("course" => "Électrotechnique",
"value" => "course3",
"emoji" => "test3"),
array("course" => "Géographie",
"value" => "course4",
"emoji" => "test4"),
);
$coll = new Collator('fr_FR');
$coll->sort($list_courses);
foreach ($list_courses as $key => $value)
{
echo ('<option value="' . "$value[value]" . '" data-icon="' . "$value[emoji]" . '">' . "$value[course]" . '</option>');
}
?>
</select>
<label for="courses">Cours</label>
With collator, it is still the same order, but with foreach, then here is the actual behaviour in the output:
Management
Géographie
Éducation Physique
Électromécanique
Collator::sort works on an array of strings - if you're passing it a multi-dimensional array then the output is going to be undefined.
You can work round this by re-indexing your array into a key->value structure instead, and then making a slight change to your loop:
// Re-index array to key=>value
$list_courses = array_column($list_courses, 'course', 'value');
// Sort by values (note asort, to maintain keys)
$coll = new Collator('fr_FR');
$coll->asort($list_courses);
foreach ($list_courses as $key => $value) {
echo '<option value="' . $key . '">' . $value . '</option>';
}
If your arrays are more complicated than this, you'll need to use a native sorting function like uasort, and make use of the Collator to do the actual comparison:
$collator = new Collator('fr_FR');
uasort($list_courses, function ($a, $b) use($collator) {
return $collator->compare($a['course'], $b['course']);
});
foreach ($list_courses as $value) {
echo '<option value="' . $value['value'] . '" data-icon="' . $value['emoji'] . '">' . $value['course'] . '</option>', PHP_EOL;
}
Here, we deal with the array objects in their entirety, so there's no need to re-index.

MultiDimensional arrays output

I am currently learning PHP and I am stuck with this problem while testing foreach with multi-dimensional arrays.
Here is my array:
$employees = array(
'Josh' => array(
'age'=>'55',
'salary'=>'105,000',
'hobbies'=> array('none')
),
'John' => array(
'age'=>'45',
'salary'=>'125,000',
'color'=>'red',
'hobbies'=> array('none')
),
'Jane' => array (
'age'=>'25',
'salary'=>'93,000',
'hobbies'=> array ('fishing', 'flying')
)
);
Whenever I try to output I always get an error of Array to string conversion or Invalid argument. Can somebody tell me how could I correctly output this multi-dimensional array using foreach?
If I do it this way, the data like 125,000, basically the value assigned to age and salary isn't written out.
foreach($employees as $names_of_employees=>$data) {
echo $names_of_employees.'<br>';
foreach($data as $specifics=>$values) {
echo $specifics.'<br>';
}
foreach($values as $hobbies) {
echo $hobbies;
}
}
If I do it this way, then it writes out, but as well it writes out "Array" and array to string error:
foreach($employees as $names_of_employees=>$data) {
echo $names_of_employees.'<br>';
foreach($data as $specifics=>$values) {
echo $specifics.$values.'<br>';
}
foreach($values as $hobbies) {
echo $hobbies;
}
}
Thanks.
Try following code
<?php
$employees = array(
'Josh' => array(
'age'=>'55',
'salary'=>'105,000',
'hobbies'=> array('none')
),
'John' => array(
'age'=>'45',
'salary'=>'125,000',
'color'=>'red',
'hobbies'=> array('none')
),
'Jane' => array (
'age'=>'25',
'salary'=>'93,000',
'hobbies'=> array ('fishing', 'flying')
)
);
foreach( $employees as $names_of_employees => $data ){
echo $names_of_employees.'<br>';
echo "Salary: ".$data['salary'].'<br>';
echo "Age: ".$data['age'].'<br>';
if( isset($data['hobbies']) && !empty($data['hobbies']) ) {
echo "Hobbies: ";
foreach( $data['hobbies'] as $hobbies ) {
echo $hobbies.'<br>';
}
}
}
Well, it depends on what you want.
foreach( $employees as $name => $data ){
echo $name;
echo $data['age'];
echo $data['salary'];
// ...etc...
}
It looks like for array element 'John' you've got an extra item in the second dimension. I believe this is ok in PHP but perhaps you have to account for this in the code you use to read the values out.
It is because you are trying to convert an array to a string. The problem is caused by hobbies since it is an array. So in your foreach loop that goes through $data you need to check if it is an array or if the key is equal to hobbies.
foreach($employees as $names_of_employees=>$data) {
echo $names_of_employees.'<br>';
foreach($data as $specifics=>$values) {
if(is_array($values)) { //or you could say if($specifics == 'hobbies')
echo $specifics . ': ' . implode(',',$values) . '<br>';
} else {
echo $specifics . ': ' . $values . '<br>';
}
}
}

create a drop down list from a multi dimensional array

I have a multi dimensional array created from a mysql query. with each index holding an array containing customer information. I want to create a drop down list from this with the value being customer ID and the text being customer name but I don't know how to access the arrays inside the main array.
I have the following function which I used to create other drop down lists from single arrays but when I try to use it with a multi dimensional array all it returns is the index numbers. (i get a list of 0, 1, 2, 3)
function createDropDown($name = '', $options = array()) {
$dropDown = '<select name="'.$name.'">';
foreach ($options as $option => $value) {
$dropDown .= '<option value='.$value.'>'.$option.'</option>';
}
$dropDown .= '</select>';
return $dropDown;
}
EDIT
its 2 dimensional, an array holding arrays of customer details.
my query is ran on a different page so I save the results into a session variable with this.
$searchtext = $_POST['searchDB'];
$query = "SELECT * FROM customer WHERE First_Name LIKE '%$searchtext%'";
$data = mysql_query($query) or die(mysql_error());
$Customers = array();
while($row = mysql_fetch_assoc($data)){
$Customers[] = $row;
}
$anymatches = mysql_num_rows($data);
if ($anymatches != 0) {
$_SESSION['names']=$Customers;
}
print_r($array) gives me the following:
Array ( [0] => Array ( [ID] => 25 [First_Name] => Maggy [Surname] => barrows [Company_Name] => squiggle [Telephone] => 12121212 [Alt_Telephone] => 4343434 [notes] => ) )
Like that:
function createDropDown($name = '', $options = array()) {
$dropDown = '<select name="'.$name.'">';
foreach ($options as $option => $value) {
$dropDown .= '<option value='.$value['ID'].'>'.$value['First_Name'].' '.$value['Surname'].'</option>';
}
$dropDown .= '</select>';
return $dropDown;
}
function createDropDown($name = '', $options = array()) {
$dropDown = '<select name="'.$name.'">';
foreach ($options as $option ) {
$dropDown .= '<option value="'.$option["name"].'">'.$option["name"].'</option>';
}
$dropDown .= '</select>';
return $dropDown;
}
Try something like the above replaceing "name" with the field name of what you want for the value and label
In your foreach, the $option => $value might be easier to understand as $key => $option. The $key is the index of the option, and the $option is the value you set.
If $value is a single-dimension array, you can just access its values by their indices ($option['id'] and $option['name'], for example).
If your options are single-dimensional, you can just access them with something like:
foreach($options as $option) {
$dropDown .= '<option value="' . $option['id'] . '">' . $option['name'] . '</option>';
}
Since you are dealing with a 2 dimensional array, or in other words one array nested within another you have to run another foreach loop like this:
function createDropDown($name = '', $options = array()) {
$dropDown = '<select name="'.$name.'">';
foreach ($options as $customer) {
foreach($customer as $info) {
$dropDown .= '<option value='.$info["id"].'>'.$info["name"].'</option>';
}
}
$dropDown .= '</select>';
return $html;
}
I'm not sure what your actual indexes within your nested array are, so you may have to tweak the above code a little bit. Good luck!

How to prevent duplicate values in a combo box

I have a view in my codeigniter app that gets an array from the database.
I want to create several combo boxes based on the contents of the array.
Here's what the array looks like:
Array (
[0] => Array (
[L1ID] => 2
[L1Location] => USA
[L2ID] => 3
[L2Location] => New York
[L3ID] => 4
[L3Location] => Manhanttan
)
[1] => Array (
[L1ID] => 2
[L1Location] => USA
[L2ID] => 8
[L2Location] => New Jersey
[L3ID] => 7
[L3Location] => Bergen County
)
[2] => Array (
[L1ID] => 5
[L1Location] => Canada
[L2ID] => 12
[L2Location] => Ontario
[L3ID] => 50
[L3Location] => Toronto
)
[3] => Array (
[L1ID] => 6
[L1Location] => South Korea
[L2ID] => 22
[L2Location] => Gyungido
[L3ID] => 25
[L3Location] => Buchon
)
)
As you can see, each item in the array can have up to 3 locations defined within.
I would like to create a combo box that has all the Location 1's in it.
So, in other words, it will have "USA", "CANADA", "SOUTH KOREA" as options. When the user clicks on any location, i want to query the same array and get the next level down - all the location 2's - populated in a separate combo box.
So for example, when they select "USA" in location 1, location 2 combo will show "New York" and "New Jersey" as options.
I've written some code to start looping through the array and extract all L1's (location 1's) but I don't know how to prevent duplicates from being added.
Here's my code:
<select id="L1locationlist" name="L1locationlist">
<option value=""></option>
<?php
foreach ($locations as $location) {
echo ($location['L1ID'].'<BR>');
echo '<option value="' . $location['L1ID'] . '">' . $location['L1Location'].'</option>';
}
?>
</select>
I only want one USA entry in the combo box.
Can you tell me how I can do this? Do I have to create a separate function to check if it already exists in the combo box?
Thank you.
EDIT:
The original plan was to get all location information once from the database, and then on the client side, somehow dynamically drill down into the different locations depending on what the user clicks.
But I guess I should also ask whether this is a good design or not? Perhaps the code will be "cleaner" if I just make separate calls to the database. So for example, I will initially just get all location 1 values. Then if the user selects "USA" i will query the db again for all sublocations in USA.
I guess the initial thought was to save multiple trips to the db.
Any comments?
The first thing I would do is parse the array to get all the ocations in the format you want it:
$parsedLocations = array(1 => array(), 2 => array(), 3 => array());
foreach ($locations as $location) {
for($i = 1; $i < 4; $i++) {
$parsedLocations[i][$location['L' . $i . 'ID']] = $location['L' . $i . 'Location']
}
}
Once you have the array you need you can simply display the items and make them unique with array_unique():
<select id="L1locationlist" name="L1locationlist">
<option value=""></option>
<?php
$locations = array_unique($parsedLocations[1]);
foreach($locations as $key => $location) {
echo ' <option vaue="' . $key . '">' . $location . '</option>';
}
?>
</select>
If you want to do this dynamically for all three locations you could do something like the following (with the same parsed locations array):
<?php
for ($i = 1; $i < 4; $i++) {
echo '<select id="L' . $i . 'locationlist" name="L' . $i . 'locationlist">';
echo ' <option value=""></option>';
$locations = array_unique($parsedLocations[1]);
foreach($locations as $key => $location) {
echo ' <option vaue="' . $key . '">' . $location . '</option>';
}
echo '</select>';
}
Loop through the $locations array and generate a new array for each box, checking values as you go. Then, loop through each of those arrays and generate the boxes. (Demo.)
<?php
$countries = array();
$states = array();
$cities = array();
foreach ($locations as $location) {
if(!array_key_exists($location['L1ID'], $countries))
$countries[$location['L1ID']] = array(
'name' => $location['L1Location'],
'states' => array(),
);
if(!array_key_exists($location['L2ID'], $countries[$location['L1ID']]['states'])){
$countries[$location['L1ID']]['states'][$location['L2ID']] = array(
'name' => $location['L2Location'],
'cities' => array(),
);
}
if(!array_key_exists($location['L3ID'], $countries[$location['L1ID']]['states'][$location['L2ID']])){
$countries[$location['L1ID']]['states'][$location['L2ID']]['cities'][$location['L3ID']] = $location['L3Location'];
}
}
// Generate $countries box
foreach ($countries as $key => $country) {
echo ($key.'<BR>'."\n");
echo '<option value="' . $key . '">' . $country['name'].'</option>'."\n";
// Generate $states box
foreach ($country['states'] as $key => $state) {
echo ($key.'<BR>'."\n");
echo '<option value="' . $key . '">' . $state['name'].'</option>'."\n";
// Generate $city box
foreach ($state['cities'] as $key => $city) {
echo ($key.'<BR>'."\n");
echo '<option value="' . $key . '">' . $city.'</option>'."\n";
}
}
}
?>
try this
$i = 1;
foreach ($locations as $location) {
if(isset($locations[$i-1]['L1Location']) && $locations[$i-1]['L1Location'] != $location['L1Location'] && $i != 1){
echo ($location['L1ID'].'<BR>');
echo '<option value="' . $location['L1ID'] . '">' . $location['L1Location'].'</option>';
$i++;
}
}
Apart from this its better if you group by L1Location in your query then no need to code like above simple foreach loop

Simple way to select chosen option in <select> from the value given by $_POST?

How can i add the selected="selected" bit to the option in an HTML <select> input from the sent $_POST data without an if statement within each option?
<?php
$options = array(1 => 'Banana', 2 => 'Apple');
foreach ($options as $key => $value) {
echo '<option value=""';
if ($key == $_POST['fruit']) echo ' selected="selected"';
echo '>'.$value.'</option>';
}
?>
Programatically, you could do it like this:
$optionNames = array('This', 'Is', 'A', 'Test');
echo '<select id="testselect" name="testselect">';
foreach($optionNames as $currentOption) {
echo '<option value="'.$currentOption.'"';
echo $_POST['testselect'] == $currentOption ? ' selected="selected"' : '';
echo '>'.$currentOption.'</option>';
}
echo '</select>';
Must confess I don't have a dev box up at the moment to test the above code, but it should be OK. (Apologies if not.) :-)
I suppose using an if statement for each option is most efficient.
But you can create an array containing empty strings except for the location of the option you want to select in order to eliminate the if statement.
$options = array(1 => 'Banana', 2 => 'Apple', 3 => 'Orange');
$selected_options = array_fill(1, sizeof($options), "");
if(array_key_exists($_POST['fruit'], $options))
$selected_options[$_POST['fruit']] = " selected=\"selected\"";
echo '<select id="fruit" name="fruit">';
foreach($options as $optionId => $optionText)
echo '<option value="'.$optionId.'"'.$selected_options[$optionId].'>'.$optionText.'</option>';
echo '</select>';

Categories