create a drop down list from a multi dimensional array - php

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!

Related

How to echo specific value from associative array in <select> for Selected attribute

can anyone help me out for this thing
$person = array(‘abb’ => ‘Abbie, ‘abi’ => ‘Abigail’, ade’ => ‘Adelaide’);
$selection = '';
foreach ($selection as $abbreviation => $name) {
$selection = $selection."<option value=$abbreviation selected=(HOW DO I ECHO Abigail HERE FOR DEFAULT OPTION)>$name</option>";
}
try this
$person = array('abb' => 'Abbie', 'abi' => 'Abigail', 'ade' => 'Adelaide');
$selection = '<select>';
foreach ($person as $abbreviation => $name) {
$selection = $selection.'<option value="'.$abbreviation.'"';
if($name=='Abigail')
$selection .= 'selected';
$selection .= ">$name</option>";
}
$selection .= '</select>';
echo $selection;
if i understand right, this is what you want

PHP - Update HTML Select list to show current value

I'm working on a simple HTML form that will include a drop down list for the selected Salesperson. The list is coming from a database and is in an array that is stored in a variable $ids and looks like this:
Array ( [John Jones] => JJ [Sally Smith] => SS [Victor Howards] => VH [Barnie Kemp] => BK )
Here's how the select list is currently constructed:
<?php
$output = "";
$selected = false;
foreach ($ids as $id => $value) {
$output .= "<option value=\"$value\"";
if ($id == $record->getField('initials')) {
$selected = true;
$output .= " selected";
$selectedID = $record->getField("id");
}
$output .= ">$id</option>";
}
if (!$selected) {
$chosen = $record->getField("initials");
$output = "<option value=\"$chosen\" selected>$chosen</option>$output";
}
echo $output;
?>
I'm trying to update the select list to show the current value for this field as the selected option. I have the name/value stored in these variables:
$initials
$name
So if $initials = 'SS' I would like Sally Smith to be the selected value in the list.
Try to use as simple as follow
<?php
$output = "";
foreach ($ids as $id => $value) {
$selected = "";
if ($id == $record->getField('initials')) {
$selected = "selected";
}
$output .= "<option value='$value' $selected>$id</option>";
}
echo $output;
?>
Do not make your code complex.. do it like this one:
$value=$record->getField('initials');
foreach ($ids as $id => $valueData) {
if($id==$value)
echo "<option value='".$id."' selected='selected' >$id</option>";
else
echo "<option value='".$id."'>$id</option>";
}

PHP comparing 2 arrays of arrays

Hi All I have 2 arrays for example in PHP as seen below:
[users] => Array ( [0] => Array ( [username] => Timothy ) [1] => Array ( [username] => Frederic ) )
[users2] => Array ( [0] => Array ( [username] => Johnathon ) [1] => Array ( [username] => Frederic ) [] => Array ( [username] => Peter))
I am trying to compare the contents of each array against each other in order to put a html element, I tried using a nested foreach as seen below:
foreach($users as $user){
foreach ($users2 as $user2){
if($user['username'] == $user2['username']){
echo "<option value=' ".$user['username']."' selected = 'selected'>".$user['username']."</option>";
break;
} else{
echo "<option value=' ".$user['username']."'>".$user['username']."</option>";
}
}
}
my issue is that the items are being echoed more than once which is ruining my select element. Any ideas on how to compare the contents of each?
I want to achieve a list of each name eg:
-Timothy
-Frederic (this should be highlighted as it is in both arrays)
-Johnathon
- Peter
I would take it in a different way.
//Create user array one
$users = array();
$users[] = array('username'=>'Timothy');
$users[] = array('username'=>'Frederic');
//create user array 2
$users2 = array();
$users2[] = array('username'=>'Johnathon');
$users2[] = array('username'=>'Frederic');
$users2[] = array('username'=>'Peter');
$temp_array = array();
foreach($users as $key => $value) {
$temp_array[$value['username']] = '';
}
foreach($users2 as $key => $value) {
$temp_array[$value['username']] = array_key_exists($value['username'], $temp_array) ? 'DUPLICATE' : null;
}
echo '<select>';
foreach($temp_array as $key_value => $status) {
echo "<option value='{$key_value}' ".(($status == 'DUPLICATE') ? 'selected style="background-color: yellow;"' : '').">{$key_value}</option>";
}
echo '</select>';
I'll let the array take care of it self, if it shares the same key, it will merge, then just flag it with "duplicate".
If there is never any duplicates as you say in each array, the following works for me. This may look a bit complicated, but read through my comments.
You can copy the code and run it in it's own page to see if it works the way you want.
<?php
//Create user array one
$users = array();
$users[] = array('username'=>'Timothy');
$users[] = array('username'=>'Frederic');
//create user array 2
$users2 = array();
$users2[] = array('username'=>'Johnathon');
$users2[] = array('username'=>'Frederic');
$users2[] = array('username'=>'Peter');
//create a new array to combine all of the data, yes, there will be duplicates
$allData = array();
//add to allData array
foreach ($users as $user) {
$allData[] = $user['username'];
}
//add to allData array
foreach ($users2 as $user2) {
$allData[] = $user2['username'];
}
//create an array that will hold all of the duplicates
$dups = array();
//add any duplicates to the array
foreach(array_count_values($allData) as $val => $c) {
if($c > 1) $dups[] = $val;
}
//remove the duplicates from the allData array
$allData = array_unique($allData);
//echo out form
echo '<select>';
foreach ($allData as $user) {
if (in_array($user, $dups)) {
echo "<option value=' ".$user."' selected = 'selected'>".$user."</option>";
}
else {
echo "<option value=' ".$user."'>".$user."</option>";
}
}
echo '</select>';
?>
However, I'm not sure what your intentions are since IF you had "Peter" and "Frederic" in BOTH arrays, you are not going to get the form you want. But, this works for what you wanted.

Pass array values into select option fields within a form?

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>';

PHP — How to determine number of parents of a child array?

I'm not so strong with arrays but I need to determine how to count the number of parents a child array has in order to determine the indenting to display it as an option in a SELECT.
So, if I have this array:
array(
'World'=>array(
'North America'=>array(
'Canada'=>array(
'City'=>'Toronto'
)
)
)
);
How would I go about determining how many parents 'City' has in order to translate that into the number of spaces I want to use as an indent?
Thanks for any help.
EDIT: Let's see if I can explain myself better:
I have this code I'm using to build the OPTIONS list for a SELECT:
function toOptions($array) {
foreach ($array as $key=>$value) {
$html .= "<option value=\"" . $key . "\" >";
$html .= $value['title'];
$html .= "</option>";
if (array_key_exists('children', $value)) {
$html .= toOptions($value['children']);
}
}
return $html;
}
print toOptions($list);
So, I'm trying to determine how to get the number of parents in order to add spaces before the title in this line:
$html .= $value['title'];
Like:
$html .= " " . $value['title'];
But, I'm not sure how to figure out how many spaces to add.
Hopefully this is more clear.
Thanks for any help so far.
$x = array(
'World'=>array(
'North America'=>array(
'Canada'=>array(
'City'=>'Toronto'
)
)
)
);
// This function do something with the key you've found in the array
function visit($name, $depth)
{
echo $name . ' has ' . $depth . ' parents.';
}
// This function visits all the contents aff $array
function find_recursive($array, $depth = 0)
{
if (is_array($array)) {
foreach ($array as $k => $value) {
visit($k, $depth + 1);
find_recursive($array, $depth + 1);
}
}
}
For visiting:
find_recursive($x);
Well. Off the top what you are dealing with is a multi dimensional array.
You could run a count w/ foreach on each level of the array, and use the count number returned +1 for each level the foreach loops through.
I'm not sure if this answers your question, but I am trying to see exactly what it is you are trying to achieve.
As you are already using a recursive function to display that data, you can just extend your function. There is no need to traverse the array more often than one time:
function getWhitespaces($count) {
$result = '';
while($count--) {
$result .= '$nbsp;';
}
return $result;
}
function toOptions($array, $level=0) {
foreach ($array as $key=>$value) {
$html .= "<option value=\"" . $key . "\" >";
$html .= getWhitespaces($level) + $value['title'];
$html .= "</option>";
if (array_key_exists('children', $value)) {
$html .= toOptions($value['children'], $level + 1);
}
}
return $html;
}
print toOptions($list);
Try the following.. Your solution screams for recursion in my mind. Its a bit ugly but it seems to work
$totraverse = array(
'Moon' => array(
'Dark Side' => "Death Valley"
),
'Halley Commet' => "Solar System",
'World' => array(
'North America' => array(
'Canada' => array(
'City' => 'Toronto'
)
), 'South America' => array(
'Argentina' => array(
'City' => 'Toronto'
)
)
)
);
function traverse($totraverse_, $path="", $count=0) {
global $array;
// echo count($totraverse_) . " count\n";
if (!is_array($totraverse_)) {
echo "returning $path and $key\n";
return array($path, $count);
} else {
foreach ($totraverse_ as $key => $val) {
echo "assting $path and $key\n";
$result = traverse($val, $path . "/" . $key, $count + 1);
if($result){
$array[]=$result;
}
}
}
echo false;
}
$array = array();
traverse($totraverse);
foreach($array as $item){
echo "{$item[0]}--->{$item[1]}\n";
}

Categories