I have an array that looks something like this:
$array = array(
'val1' => array('en'=>'Option Title 1','a'=>1),
'val2' => array('en'=>'Option Title 2','b'=>2),
'val3' => array('en'=>'Option Title 3','c'=>3)
);
I tried running this code to generate a select box :
function setOptions($array){
echo '<select name="select">';
foreach($array as $key_parent => $val_parent){
foreach($val_parent as $key => $val){
if($key !== 'en'){
$option_value = $val;
}elseif($key == 'en'){
$option_title = $val;
}
}
echo '<option value"'.$option_value.'">'.$option_title.'</option>';
}
echo '<select>';
}
This prints what I expected.
<select name="select">
<option value="1">Option Title 1</option>
<option value="2">Option Title 2</option>
<option value="3">Option Title 3</option>
</select>
However when I print the return value of $_POST['select'] from a form submission, I get Option Title 1, Option Title 2, or Option Title 3, not 1,2 or 3 which I thought was pretty odd.
So this leaves the question, how do I get the values inside of val1, val2, val3 when the key of one of the values in question is unknown(either a,b or c)?
You miss equal in value attribute.
function setOptions($array){
echo '<select name="select">';
foreach($array as $key_parent => $val_parent){
foreach($val_parent as $key => $val){
if($key !== 'en'){
$option_value = $val;
}elseif($key == 'en'){
$option_title = $val;
}
}
echo '<option value="'.$option_value.'">'.$option_title.'</option>';
}
echo '<select>';
}
Related
I have the following array:
$selects = array(
'Select1' => array('select1_name' => array('select1_value1','select1_value1')),
'Select2' => array('select2_name' => array('select2_value1','select2_value2'))
);
I wonder how I can generate these "selects inputs" with their options through a loop?
You need one cycle, which will loop through selects array and inside this cycle, you need another one, which will loop through selects. And inside this one, you need one more, which will loop through the option values:
$selects = array(
'Select1' => array('select1_name' => array('select1_value1','select1_value1')),
'Select2' => array('select2_name' => array('select2_value1','select2_value2'))
);
foreach($selects as $select) {
foreach($select as $item) {
echo "<select>";
foreach($item as $value) {
echo "<option value=".$value.">".$value."</option>";
}
echo "</select>";
}
}
This will produce:
<select>
<option value=select1_value1>select1_value1</option>
<option value=select1_value1>select1_value1</option>
</select>
<select>
<option value=select2_value1>select2_value1</option>
<option value=select2_value2>select2_value2</option>
</select>
foreach($selects as $select) {
foreach($select as $selectName => $value) {
echo '<select> ';
echo '<option>'.$selectName.'</option>';
foreach($value as $v) {
echo '<option>'.$v.'</option>';
}
echo '</select>';
}
}
echo '<select> ';
foreach($selects as $array) {
foreach($array as $value) {
foreach($value as $v) {
echo '<option value="'.$v.'">'.$v.'</option>';
}}}
echo '</select>';
I am comparing three arrays in nested foreach conditions. Following are the arrays
Array
(
[master/city] => City
[master/national_holiday] => National Holiday
[master/operator_comments] => Operator Comments
[master/sensors] => Sensors
[master/modbus] => Modbus
[master/manufacturers] => Manufacturers
[master/make_model] => Make Model
[master/dispatch_vendors] => Dispatch Vendors
)
Array
(
[1] => View
[2] => Write
)
Array
(
[master/city] => 1
[master/national_holiday] => 2
[master/operator_comments] => 1
[master/sensors] => 2
[master/modbus] => 1
[master/manufacturers] => 2
[master/make_model] => 1
)
Now the scenario is as follows:-
My first foreach iteartes first array
Then in the same foreach i m using second foreach which itrates second array
again in second foreach i m using third foreach to iterate third array
In third foreach , i m comparing key of first array with the key of second array and comparing value of second array with key of third array
If above condition is satisfied then in my dropdown the specific option will append selected Like <option value="1" selected="">View</option>
I am using following code
<?php
$first_array = first_array();
$i = 1;
foreach($first_array as $k => $val) {
?>
<tr>
<td>{{ $i }}</td>
<td class="mailbox-name">{{ $val }}</td>
<td><?php $second_array = second_array(); ?>
<select class="form-control master-menu" name="master_menu[{{$k}}]">
<option value="">Select Role</option>
<?php
foreach ($second_array as $key => $value) {
foreach ($third_array as $mkey => $mval) {
?>
<option value="<?php echo $key; ?>"
<?php if (($mkey == $k) && ($mval == $key)) { echo "selected"; } ?>><?php echo $value; ?></option>
<?php } } ?>
</select>
</td>
</tr>
<?php $i++; } ?>
I am using above code and getting issue that in second array there two values and in third array five values so in my dropdown count of option are ten insted of two.
This is my output.
Please suggest me.
Maybe something like this? I have simplified the process to demonstrate what is happening. I have also added the correct select values:
foreach ($first_array as $key => $value) {
?>
<p><?php echo $value; ?></p>
<?php foreach ($second_array as $second_key => $second_value) { ?>
<?php if ($key == $second_key) { ?>
<select>
<?php foreach ($third_array as $third_key => $third_value) { ?>
<option <?php echo ($third_key == $second_value ? 'selected=selected' : null); ?>><?php echo $third_value; ?></option>
<?php } ?>
</select>
<?php } else { ?>
<select>
<?php foreach ($third_array as $third_key => $third_value) { ?>
<option ><?php echo $third_value; ?></option>
<?php } ?>
</select>
<?php } ?>
<?php } ?>
<?php
}
For example you may try this code
foreach ($tmparray as $innerarray) {
//check type
if (is_array($innerarray)) {
//echo through inner loop
foreach ($innerarray as $value) {
echo $value;
}
} else {
//one,two,three
echo $innerarray;
}
}
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've wrote a simple array, and I would use it to print an html list option set, with a selected element.
My problem starts if I try to print multiple lists in my page, because only the first list is printed correctly, why?
<?php
$units = array (
'0' => 'Units',
'kJ' => 'Kilojoule: kJ',
'g' => 'Grams: g',
'mg' => 'Milligrams: mg',
'mcg' => 'Micrograms: mcg, µg');
function unit_select_option ($attributes, $code = "") {
global $units;
$html = "<select title=\"Kilojoule: kJ;
Grammi: g;
Milligrammi: mg;
Microgrammi: mcg, µg;\" $attributes>\r";
while (list($key, $name) = each($units)) {
if ($key == "0") {
$html .= " <option title=\"$name\" value='$key'>$name</option>\r";
} else if ($key == $code) {
$html .= " <option title=\"$name\" selected=\"selected\" value='$key'>$key</option>\r";
} else {
$html .= " <option title=\"$name\" value='$key'>$key</option>\r";
}
}
$html.= "</select>\r";
return $html;
}
print unit_select_option ('class="units_select"', "g");
print unit_select_option ('class="units_select"', "mg");
print unit_select_option ('class="units_select"', "mcg");
?>
the code shouldn't be nothing strange but I haven't found the issue because the page doesn't return any error.
html code:
<select title="Kilojoule: kJ;
Grammi: g;
Milligrammi: mg;
Microgrammi: mcg, µg;" class="units_select">
<option title="Unità" value='0'>Unità</option>
<option title="Kilojoule: kJ" value='kJ'>kJ</option>
<option title="Grammi: g" selected="selected" value='g'>g</option>
<option title="Milligrammi: mg" value='mg'>mg</option>
<option title="Microgrammi: mcg, µg" value='mcg'>mcg</option>
</select>
<select title="Kilojoule: kJ;
Grammi: g;
Milligrammi: mg;
Microgrammi: mcg, µg;" class="units_select">
</select>
<select title="Kilojoule: kJ;
Grammi: g;
Milligrammi: mg;
Microgrammi: mcg, µg;" class="units_select">
</select>
each() advances the internal array cursor. Because $units is a global variable, your first call of unit_select_option() advances the cursor to the end of $units, and there it remains for the subsequent calls.
You need to rewind your array using reset($units); at the end of unit_select_option().
PHP Documentation: reset
You should reset the array pointer: use reset()
But why don't you use a foreach loop?
foreach($units as $key => $name){ ... }
And don't use global, it's evil. Declare $units array as static within the function body.
From each():
Return the current key and value pair
from an array and advance the array
cursor.
After each() has executed, the array
cursor will be left on the next
element of the array, or past the last
element if it hits the end of the
array. You have to use reset()
if you want to traverse the array
again using each.
So:
function unit_select_option ($attributes, $code = "") {
global $units;
$html = "<select title=\"Kilojoule: kJ;
Grammi: g;
Milligrammi: mg;
Microgrammi: mcg, µg;\" $attributes>\r";
reset($units);
while (list($key, $name) = each($units)) {
if ($key == "0") {
$html .= " <option title=\"$name\" value='$key'>$name</option>\r";
} else if ($key == $code) {
$html .= " <option title=\"$name\" selected=\"selected\" value='$key'>$key</option>\r";
} else {
$html .= " <option title=\"$name\" value='$key'>$key</option>\r";
}
}
$html.= "</select>\r";
return $html;
}
I tend to avoid each() because its non-reentrant, meaning if inside your loop you call something else that uses it on the same array it'll affect your outer call. Not good. You tend to be better off just using a foreach loop:
function unit_select_option ($attributes, $code = "") {
global $units;
$html = "<select title=\"Kilojoule: kJ;
Grammi: g;
Milligrammi: mg;
Microgrammi: mcg, µg;\" $attributes>\r";
foreach ($units as $key => $name) {
if ($key == "0") {
$html .= " <option title=\"$name\" value='$key'>$name</option>\r";
} else if ($key == $code) {
$html .= " <option title=\"$name\" selected=\"selected\" value='$key'>$key</option>\r";
} else {
$html .= " <option title=\"$name\" value='$key'>$key</option>\r";
}
}
$html.= "</select>\r";
return $html;
}
and you avoid all those issues.
You need to reset your array after or before your while block.
The other answers should have already solved your question.
I want to add that PHP has the foreach construct, so instead of the while loop you can just write
foreach ($unit as $key => $name) {
...
}
You don't need to reset() if you use foreach.
Ok, as others have said the problem was because you weren't resetting the global array.
However, I'd be tempted not to use a global and instead pass it into the unit_select_option every time. (Arrays and objects are passed by reference in recent versions of PHP, so there's no reason not to do this and it's generally accepted as better programming practice.)
Secondly, you're doing some wierd things in the while loop - I'd have thought a foreach iterator would make more sense in this instance as such:
foreach($units as $key => $value)
Just an idea. :-)
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>';