Below is my code I am trying to get to work but I really have very little knowledge of array and foreach. So it doesn't work correctly
I need to show a dropdown select form to the browser with the contents of the array
I also need to have the item selected if it is == to $mycountry
Lastly, I would like to show the USA and UK at the top of my list
Can anyone tell me how I can do al this
<?PHP
$countries = array(
"217" => "Turkenistan",
"218" => "Turks and Caicos Islands",
"219" => "Tuvalu",
"220" => "Uganda",
"221" => "Ukraine",
"222" => "United Arab Emirates",
"223" => "United Kingdom (Great Britain)",
"224" => "United States");
$mycountry = 224;
?>
<select name="country" style="width:180px;" onChange="do_get_rest_popup(this.value)" />
<?php
$countryCounter = 1;
$amtOfCountries = count($countries);
//foreach ($country as $id => $c) {
for( $_top=0; $_top < $amtOfCountries; $_top++ ){
if ($countryCounter == $amtOfCountries) {
echo "<option value=\"$countries[0]\" SELECTED>$countries[1]</option>";
} else {
echo "<option value=\"$countries[0]\">$countries[1]</option>";
$countryCounter++;
}
}
?>
</select>
foreach ($countries as $key => $country) {
$selected = ""
if ($key == $mycountry) $selected = ' selected="selected" ';
print '<option value=' . $key . $selected . '>' . $country . '</option>';
}
Basically, for every element within the array, you are breaking it into its key and its value (ie $countreis[key] = value). Once you get your head around arrays (and they can be very confusing) it will make coding a million times easier.
(For some reason the syntax highlighting / formatting is not working in my code...)
I'm going to guess you are looking for:
foreach($countries as $id => $country) {
echo '<option value="$id"' . ($mycountry==$id?'selected="selected"':'') . '>' . $country . '</option>';
}
As for making sure that the U.S. and U.K. are on top, make sure that those 2 are on top of your array (that would be the very easiest).
You should put US and UK at the top of your array and then use something like:
foreach($countries as $row => $value) {
echo "<option value=\"$row\"" + ($row == 'usa' ? 'SELECTED') + ">$value</option>";
}
and you should use selected="selected" instead of SELECTED
Related
I am trying to evaluate date[3] to determine selected option. All this is inside a php sql query. I am not able to find out an easy way to get a selected for the value returned in date[3] in my $options string variable.
<?php //sql statement
foreach( $db->query($sql) as $data ) {
$options = "<select type='text' name='pagephone' select id='pagephone' >
<option value=''></option>
<option ". if ($data[3] == 'vtext.com' ){ echo 'selected' };. " value='vtext.com'>Verizon Wireless</option>
<option ". if ($data[3] == 'vmobl.com' ){ echo 'selected' };. " value='vmobl.com'>Virgin Mobile</option>
<option ". if ($data[3] == 'sms.alltelwireless.com' ){ echo 'selected' };. " value='sms.alltelwireless.com'>Alltel</option>";
?>
You're trying to concatenate a value with ., so the value you use needs to be an expression that evaluates to a string. An if block is not such an expression, as you can see from the syntax error you get if you use the code from your question. You can use a ternary expression instead, like this.
...<option ". ($data[3] == 'vtext.com') ? 'selected' : '' . " value='vtext.com'>
Verizon Wireless</option>...
Personally, I would prefer to iterate an array of value/text pairs rather than hardcoding all the select options, like this:
$values = [
'vtext.com' => 'Verizon Wireless',
'vmobl.com' => 'Virgin Mobile',
'sms.alltelwireless.com' => 'Alltel'
];
foreach( $db->query($sql) as $data ) {
$options = "<select type='text' name='pagephone' id='pagephone'><option value=''></option>";
foreach ($values as $value => $text) {
$selected = ($data[3] == $value) ? 'selected' : '';
$options .= "<option value='$value' $selected>$text</option>";
}
$options .= '</select>';
}
But that's just my opinion. Don't forget to close your <select>, though.
code snippet from html_form_class
<?php
$frmStr = $frm->addSelectList(
'city',
$city,
true,
'',
'--- Select City ---',
array(
'class' => 'dropdown-style5',
'id' => 'city'));
echo $frmStr; ?>
code snippet from seachcar.php
$city = $db->select('City','City_Name');
foreach($city as $row)
{
$row;
}
"Array" is displaying in dropdown instead of values fetched from database
Please Advice!
function addSelectList($name, $option_list, $bVal = true, $selected_value = NULL,
$header = NULL, $attr_ar = array() ) {
$str = "<select name=\"$name\"";
if ($attr_ar) {
$str .= $this->addAttributes( $attr_ar );
}
$str .= ">\n";
if ( isset($header) ) {
$str .= " <option value=\"\">$header</option>\n";
}
foreach ( $option_list as $val => $text ) {
$str .= $bVal? " <option value=\"$val\"": " <option";
if ( isset($selected_value) && ( $selected_value === $val || $selected_value === $text) ) {
$str .= $this->xhtml? ' selected="selected"': ' selected';
}
$str .= ">$text</option>\n";
}
$str .= "</select>";
return $str;
}
html output of addSelectList function is
<select name="city" class="dropdown-style5" id="city">
<option value="">--- Select City ---</option>
<option value="0">Array</option>
<option value="1">Array</option>
<option value="2">Array</option>
<option value="3">Array</option>
You need to rebuild the array of cities:
$city = $db->select('City','City_Name');
$city_rebuild = array();
foreach($city as $row) {
$city_rebuild[] = $row['City_Name'];
}
$city = $city_rebuild;
You do echo of array. Something is wrong in your abstraction objects. You must iterate on array to show up its values.
function addSelectList creates a "dropdown" (actually a select element)
You need to remove the html from the function output.
Edit 1
I was confused as to what you were going for. In your foreach($option_list... you need to know what keys are available in the $option_list array and what you want to appear in the select dropdown.
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
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>';
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>';