I have seen many similar issues but none that can help explain my issue.
I have an array called cities, with a nested array for the state that has the cities of that state. It looks like this:
$cities = array(
"ca" => array(
"los-angeles" => "Los Angeles"
),
"wa" => array(
"bellingham" => "Bellingham",
"seattle" => "Seattle",
"tacoma" => "Tacoma"
)
);
My PHP code to display many HTML select fields:
<?php
foreach ($cities as $state) {
echo "<select name='city' id='" . $state . "'>";
foreach ($state as $city => $name) {
echo "<option value='" . $city . "'>" . $name . "</option>";
}
}
?>
The id of the select is always Array. How can I use the key, like "ca" or "wa"?
The problem is that you should be using the array key for the select on the states. Here is my revision of your code. Note that I explicitly have named state_key and state_value as well as city_key and city_value. Naming things explicitly like this helps in debugging. I also added a closing </select> element so the content renders correctly.
foreach ($cities as $state_key => $state_value) {
echo "<select name='city' id='" . $state_key . "'>";
foreach ($state_value as $city_key => $city_value) {
echo "<option value='" . $city_key . "'>" . $city_value . "</option>";
}
echo "</select>";
}
That's because the first foreach loop is going over an array of arrays. So each member is going to be an array. If you had id ='" . $state[0] you would see the first member of said array.
the var_dump function is your friend.
You could get all the cities by using array_keys function.
foreach ($cities as $key=>$state) {
echo "<select name='city' id='" . $key . "'>";
foreach ($state as $city => $name) {
echo "<option value='" . $city . "'>" . $name . "</option>";
}
}
change to this
in your case $state is an array containing cities. so it is always showing the value as Array().
Try uisng echo "<select name='city' id='" . $state['los-angeles'] . "'>"; instead of echo "<select name='city' id='" . $state . "'>";
If you want ca as your select element id then use below one,
foreach ($cities as $key=>$state) {
echo "<select name='city' id='" . $key . "'>";
foreach ($state as $city => $name) {
echo "<option value='" . $city . "'>" . $name . "</option>";
}
}
If you want like los-angeles as id of your select element, then use below one
foreach ($cities as $key=>$state) {
$SelectId = strtolower(str_replace(" ",'-',$state['los-angeles']));
echo "<select name='city' id='" . $SelectId . "'>";
foreach ($state as $city => $name) {
echo "<option value='" . $city . "'>" . $name . "</option>";
}
}
Related
I am using the following code. I take some values from an xml, then I use as html option. I am using almost the same code for the first and second select. First option show in the select menu the right values: http://vilavaleaprahovei.ro/kimea/anvelope.php, but the other one shows 0. Could somebody to tell me what to do on the "Eficienta combustibil" to show the right values?
<form action="anvelope.php" method="post">
<?php
$jante = "http://vilavaleaprahovei.ro/kimea/feeds/alcarRO_feed.xml";
$xml=simplexml_load_file($jante);
$items = [];
$limitItems = 0;
foreach($xml->Produs as $child)
{
$marca = (string)$child->Marca;
if(!isset($items[$marca])) {
$items[$marca] = [];
}
$items[$marca]['sarcina'][] = (int)$child->Sarcina;
$items[$marca]['eficienta_combustibil'][] = (float)$child->Eficienta_Combustibil;
}
//SARCINA
$option_arr9 = array_column($items,'sarcina');
function generate_option9($item, $key)
{
echo "<option value='" . $item . "'>" . $item . "</option>";
}
$options = array_unique($option_arr9[0], SORT_STRING); // You can add array_unique and SORT_NUMERIC here
asort($options);
echo "<select name='sarcina'><option>Sarcina</option>";
array_walk_recursive($options, 'generate_option9');
echo "</select>";
//EFICIENTA COMBUSTIBIL
$option_arr10 = array_column($items,'eficienta_combustibil');
function generate_option10($item, $key)
{
echo "<option value='" . $item . "'>" . $item . "</option>";
}
$options = array_unique($option_arr10[3], SORT_STRING); // You can add array_unique and SORT_NUMERIC here
asort($options);
echo "<select name='eficienta_combustibil'><option>Eficienta Combustibil</option>";
array_walk_recursive($options, 'generate_option10');
echo "</select>";
?>
</form>
I want to make an array of various inputs. For example that my key is submit button, and I want that my array key would be a content of what my submit button needs, also my button is connected to text field.
My minimal code:
<?php
function element($submit){
if ($submit == "submit"){
$element = "<input type = $submit value = $submit /><INPUT type = $submit name = $submit value = $submit size=40 />";
}
$content = $element ;
return $content;
} // function element
function main($submit){
//print_r ($defaults);
foreach ($submit as $k=>$submit){
#$content .=element ($submit[$k]) . "<br />\n";
}
return "<form action = {$_SERVER['PHP_SELF']} method = POST>\n$content</form>";
}
$arr = array(
"submit" => array("submit", "OK","text", "question", ""),
);
$content .= main ($arr["submit"]);
print $content;
So the problem is I don't know how to put my key array values into HTML. Maybe I am doing it wrong? And is it bad practice to do like this?
This is outputting the inputs I believe like you want. There are comments in the code for what I changed and some thoughts.
<?php
//Change param to $name of the index and $data that you will usefor readability
function element($name, $data){
//Checking that we are on the right element
$element = "";
if ($name == "submit"){
//It is confusing that you have 2 inputs here.
//Rather than hard coding 0, 1, 2, 3, 4 there could be a name
//in an associative array. This is not very flexible
//This is string interpolation I like it more hen concatenation for
//Simple put this variable here
$element = "<input type='{$data[0]}' value='{$data[1]}' /><input type='{$data[2]}' name='{$data[3]}' value='{$data[4]}' size=40 />";
}
//No need to do $content = $element then just return
//Not sure what should happen if the name does not exist...
//Right now it is an empty string
return $element;
}
function main($inputs){
//print_r ($defaults);
//Create this before just using it removes a warning.
$content = '';
//Change to $v just for clarity not sure what it will do to actual $submit.
//Loops the whole array not just that instances of submit.
foreach ($inputs as $k=>$v){
$content .= element ($k, $v) . "<br />\n";
}
return "<form action = {$_SERVER['PHP_SELF']} method = POST>\n$content</form>";
}
//Changed to inputs assuming this would be more then one
$inputs = array(
"submit" => array("submit", "OK","text", "question", ""),
);
//Lets call this form you are overusing the content and it is hard to follow
$form = main($inputs);
print $form;
You can embed variable values into a string by using the . (dot) operator in PHP (this is generally called "string concatenation"). For your code I would do it like this:
$element = "<input type='" . $btnname . "' value='" . $btnvalue . "'/><input type='" . $fieldtype . "' name=" . $fieldname . " value='" . $fieldvalue . "' size='40' />";
Or using an array (which must be defined first):
$element = "<input type='" . $sub[0] . "' value='" . $sub[1] . "' /><input type='" . $sub[2] . "' name=" . $sub[3] . " value='" . $sub[4] . "' size='40' />";
If you have an (multi-dimensional) array (with keys which are also arrays), say
$arr = array("subkey" => array($firstVar, $secondVar, [...]));
then you have to use the string concatenation like this:
$element = "<input type='" . $arr["subkey"][0] . "' value='" . $arr["subkey"][1] . "' /><input type='" . $arr["subkey"][2] . "' name=" . $arr["subkey"][3] . " value='" . $arr["subkey"][4] . "' size='40' />";
This will also work for more array subkeys (more dimensions).
You could also use string indices in your array, like the ones of $_SERVER, $_GET or $_POST by replacing the integer index by a string.
But you do not have to have a submit button connected to a text field, it can exist alone.
Ive got a pretty basic table named 'customers' with four columns:
ID (primary Auto Increment)
businessName
contactName
contactEmail
I call it with:
$result = mysqli_query($con, "SELECT * FROM customers");
and was using mysqli_fetch_array to display it on the page with a foreach loop:
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "<td><a href='updateform.php?id=" . $row['id'] . "'>Edit</a></td>";
echo "</tr>";
}
Which gives you an array like:
Array ( [id] => 1 [businessName] => Microsoft [contactName] => Bill Gates [contactEmail] => bill#microsoft.com ) Array ( [id] => 2 [businessName] => Amazon [contactName] => Jeff Bezos [contactEmail] => jeff#amazon.com )
Is it possible to display results differently based on which column (technically now position in the array) they are in? I would like to make a
a href="mailto:bill#microsoft.com"
link when it gets to contactEmail.
What if I wanted to display just one key or value instead of using foreach?
It doesn't seem possible to call
$row['contactEmail']
in the foreach loop
which confuses me since below that I am able to create a link to
$row['id']
If anyone has any ideas how to do this, or if there is a better way to be displaying this information, I'm open to suggestions, as I'm not very good at programming, especially PHP.
Yes! you can just add like this:
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo "<tr>";
foreach ($row as $key => $value) {
if($key == "contactEmail"){
$mailUrl = "mailto:".$value;
echo "<td>".$value."";
}
else{
echo "<td>" . $value . "</td>";
}
}
echo "<td><a href='updateform.php?id=" . $row['id'] . "'>Edit</a></td>";
echo "</tr>";
}
Yes, You can able to mysqli_fetch_array retrieve data directly using foreach loop. like bellow :
<?php
$result = mysqli_query($con, "SELECT * FROM customers");
?>
<table>
<tr>
<td>Business Name</td>
<td>Contact Name</td>
<td>#</td>
</tr>
<?php
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo "<tr>";
echo "<td>".$row['businessName']."</td>";
foreach ($row as $key => $value) {
$newValue = $key == "contactEmail" ? ''.$value.'' : $value;
echo "<td>" . $newValue . "</td>";
}
echo "<td><a href='updateform.php?id=" . $row['id'] . "'>Edit</a></td>";
echo "</tr>";
}
?>
</table>
I was wondering if someone could help me. I want to iterate through an associative array and put the results into two combo boxes. The combo boxes will have the exact same data in each other.
while ($this->results = $this->dbhandle->fetch(PDO::Fetch_Assoc))
{
echo "<option value='" . $this->result['id] . "'>"
. $this->result['name'] . "</option>";
}
Do I have to run this loop twice for 2 seperate comboboxes or is there a more efficient way of doing this?
Your best bet in this situation is to just accumulate the text in a string and echo it out twice.
$options = "";
while ($this->results = $this->dbhandle->fetch(PDO::Fetch_Assoc))
{
$options.= "<option value='" . $this->result['id] . "'>"
. $this->result['name'] . "</option>";
}
echo "<select name='combo1'>".$options."</select>";
echo "<select name='combo2'>".$options."</select>";
How about something like this (raw code to give you an idea):
while
{
$combo_options .= "<option>" ....// rest of your code
}
Then print the variable inside your selects:
<select id="combo1"><?=$combo_options?></select>
<select id="combo2"><?=$combo_options?></select>
You can capture the output as a variable and then echo it as needed
while ($this->results = $this->dbhandle->fetch(PDO::FetchAssoc)){
$output .= "<option value='" . $this->result['id'] . "'>" . $this->result['name'] . "</option>";
}
/// later on in your script
print $output;
I'm coding the locations for groups, and the user can search based on the location to find the nearest group to them. The fields are: country, state, city, neighborhood. Let's say there are ten groups in the USA -- I don't want it to list the option USA ten times. I added in a strpos so that it will only list them once, but I'm getting an error.
Here's the php code:
<?php
$myQuery = "select country, state, city, neighborhood from groups WHERE group_status = 'open to new members'";
$rs = mysql_query($myQuery);
$country_options = $state_options = $city_options = $neighborhood_options = '';
while($get_row = mysql_fetch_assoc($rs)){
$pos_country = strpos($get_row['country'], $country_options);
if($pos_country === false) {
echo $country_options .= "<option value='" . $get_row['country'] . "'>" . $get_row['country'] . "</option>";}
$pos_state = strpos($get_row['state'], $state_options);
if($pos_state === false) {
echo $state_options .= "<option value='" . $get_row['state'] . "'>" . $get_row['state'] . "</option>";}
$pos_city = strpos($get_row['city'], $city_options);
if($pos_city === false) {
echo $city_options .= "<option value='" . $get_row['city'] . "'>" . $get_row['city'] . "</option>";}
$pos_neighborhood = strpos($get_row['neighborhood'], $neighborhood_options);
if($pos_neighborhood === false) {
echo $neighborhood_options .= "<option value='" . $get_row['neighborhood'] . "'>" . $get_row['neighborhood'] . "</option>";}
}
?>
It outputs the following errors:
Warning: strpos(): Empty delimiter in sidebar.php on line 66
Warning: strpos(): Empty delimiter in sidebar.php on line 70
Warning: strpos(): Empty delimiter in sidebar.php on line 73
Warning: strpos(): Empty delimiter in sidebar.php on line 76
Underneath the error it has a nice form with the correct fields: country, state, city, neighborhood. It's just listing the same countries multiple times.
The delimiter for strpos() is the second parameter passed in.
In your code, you start out with:
$country_options = $state_options = $city_options = $neighborhood_options = '';
These are each the values you use as delimiters, and they are all empty - hence your error. After you perform your strpos() checks using a given key, then you set it. For instance:
$pos_country = strpos($get_row['country'], $country_options);
if($pos_country === false) {
echo $country_options .= "<option value='" . $get_row['country'] . "'>" . $get_row['country'] . "</option>";
}
I'm not sure what character you're searching for with $country_options, but you immediately append a <option></option> tag to it (which is one really long delimiter). Are you, perhaps, using the wrong variables as the characters you're searching for?
EDIT
After re-reading your question, I understand the goal you're trying to achieve (I think). You simply don't want to display the same country, state, city, or neighborhood more than once.
To accomplish this, it may be easier to keep an array of "seen" values and just check that array in each loop. Try something like this:
$countries = array();
$states = array();
$cities = array();
$neighborhoods = array();
while($get_row = mysql_fetch_assoc($rs)) {
if (!in_array($get_row['country'], $countries)) {
$country_options .= '<option value="' . $get_row['country'] . '">' . $get_row['country'] . '</option>';
$countries[] = $get_row['country'];
}
if (!in_array($get_row['state'], $states)) {
$state_options .= '<option value="' . $get_row['state'] . '">' . $get_row['state'] . '</option>';
$states[] = $get_row['state'];
}
if (!in_array($get_row['city'], $cities)) {
$city_options .= '<option value="' . $get_row['city'] . '">' . $get_row['city'] . '</option>';
$cities[] = $get_row['city'];
}
if (!in_array($get_row['neighborhood'], $neighborhoods)) {
$neighborhood_options .= '<option value="' . $get_row['neighborhood'] . '">' . $get_row['neighborhood'] . '</option>';
$neighborhoods[] = $get_row['neighborhood'];
}
}