Put an array within an array, display a drop down in php - php

I am trying to create a form using php. I am unsure how to put the country drop down menu right after the city field. I am not sure the best way to do this I have my array.
$labels = array (
"first_name" => "First Name",
"last_name" => "Last Name",
"address" => "Address",
"city" => "City",
"email" => "E-mail",
"phone" => "Phone", );
$country = array (
"select" => "",
"us" => "United States",
"ca" => "Canada",
"mx" => "Mexico", );
$submit = "Submit";
?>
Here is the display code:
<?php
echo "<h2>Customer Info</h2>";
echo "<form action='checkBlank.php' method='post'>";
foreach ( $labels as $field => $label)
{
echo "<div class='field'>
<label for='$field'>$label</label>
<input id='$field' name='$field' type='text'
size='42' /></div>";
if($field == "city") {
echo "<label for='country'>Country</label>
<select id='country' name='country'>";
foreach ( $country as $select => $option)
{
echo "<option value='$value'>$option</option>";
}
echo "</select>";
}
}
echo "<div id='submit'>
<input type='submit' value='$submit'></div>
</form>";
?>

Test the field name, and if it's the city, do another loop to display the country drop-down.
foreach ( $labels as $field => $label)
{
echo "<div class='field'>
<label for='$field'>$label</label>
<input id='$field' name='$field' type='text'
size='42' /></div>";
if ($field == 'city') {
echo '<div><select name="country">';
foreach ($country as $short => $long) {
echo "<option value='$short'>$long</option>";
}
echo '</select></div>';
}
}
BTW, it's conventional to use an empty value for the Select One option. Standard form validation tools will recognize this as meaning no option was selected, if you mark the field as required.

'Looks like #Barmar beat me to the punch on this one but i have a similar solution
$labels = array (
"first_name" => "First Name",
"last_name" => "Last Name",
"address" => "Address",
"city" => "City",
"email" => "E-mail",
"phone" => "Phone", );
$country = array (
"select" => "Select One",
"us" => "United States",
"ca" => "Canada",
"mx" => "Mexico", );
$submit = "Submit";
echo "<h2>Customer Info</h2>";
echo "<form action='checkBlank.php' method='post'>";
foreach ( $labels as $field => $label)
{
echo "<div class='field'>
<label for='$field'>$label</label>
<input id='$field' name='$field' type='text'
size='42' /></div>";
if($field == "city") {
echo "<label for='country'>Country</label><select id='country' name='country'>";
foreach ( $country as $value => $option)
{
echo "<option value='$value'>$option</option>";
}
echo "</select>";
}
}
echo "<div id='submit'>
<input type='submit' value='$submit'></div>
</form>";

I would personally do it like this:
$fields = array (
array(
"name" => "first_name",
"label" => "First Name",
),
array(
"name" => "last_name",
"label" => "Last Name",
),
array(
"name" => "address",
"label" => "Address",
),
array(
"name" => "city",
"label" => "City",
),
array(
"name" => "country",
"label" => "Country",
"options" => array (
"" => "Select One",
"us" => "United States",
"ca" => "Canada",
"mx" => "Mexico",
),
),
array(
"name" => "email",
"label" => "E-mail",
),
array(
"name" => "phone",
"label" => "Phone",
),
);
foreach($fields as $field) {
echo "<div class='field'><label for='{$field['name']}'>{$field['label']}</label>";
if (isset($field['options'])) {
echo "<select name='{$field['name']}'>";
foreach ($option as $value => $title) {
echo "<option value='$value'>$title</option>";
}
echo '</select>'
} else {
echo "<input id='{$field['name']}' name='{$field['name']}' type='text' size='42' />";
}
echo "</div>";
}

Related

Loop into a multidimensional array in PHP

I have this array in PHP:
array(
"name" => "Cherry",
"desc" => "I'm a cherry.",
"keys" => array(
"Africa",
"India",
"America"
),
"pict" => "image1.png",
)
And I want to loop into this and between keys to display to countries/continents.
This is what I have already tried:
foreach($details as $detail) {
foreach($keys as $key) {
echo $key;
}
}
In case if you want to get other values in array along with countries:
<?php
$details = array(
"name" => "Cherry",
"desc" => "I'm a cherry.",
"keys" => array(
"Africa",
"India",
"America"
),
"pict" => "image1.png",
);
foreach( $details as $key => $detail ) {
if( is_array( $detail ) && $key == 'keys' ) {
foreach( $detail as $country ) {
echo $country;
}
} else {
echo $detail;
}
}
?>

Converting a PHP array into HTML form inputs is duplicating items

I am attempting to take an array of values and build a php form from those values.
The array is at the bottom to keep the question clear. The array structure is:
- Item
- Item
- Item with Child
-Item
-Item
- Item with Child
-Item
-Item
Here is what I want to output each item but if the item has a child, just output the name of the parent and create fields for the children.
I created this:
function renderTest2(array $data)
{
$html = '<ul>';
foreach ($data as $item) {
$html .= '<li>';
foreach ($item as $key => $value) {
if (is_array($value)) {
$html .= renderTest2($value);
} else {
if (array_key_exists('children', $item)) {
$html .= $item['name'];
} else {
$html .= $item['name'] . "<input type=\"text\" value=\"\"> <br/>";
}
}
}
$html .= '</li>';
}
$html .= '</ul>';
return $html;
}
Which gave me this output:
But I don't understand why it is duplicating items. What am I doing wrong?
Here is the test array I used:
$aFullArray = array();
$aFullArray[] = array("name" => "Adam", "address" => "123 main", "phone" => "000-000-0000");
$aFullArray[] = array("name" => "Beth", "address" => "123 main", "phone" => "000-000-0000");
$aChildren = array();
$aChildren [] = array("name" => "Mike", "address" => "123 main", "phone" => "000-000-0000");
$aChildren[] = array("name" => "Nancy", "address" => "123 main", "phone" => "000-000-0000");
$subChild = array();
$subChild [] = array("name" => "Peter", "address" => "123 main", "phone" => "000-000-0000");
$subChild [] = array("name" => "Paul", "address" => "123 main", "phone" => "000-000-0000");
$aChildren [] = array("name" => "Oscar", "address" => "123 main", "phone" => "000-000-0000",
"children" => $subChild);
$aFullArray[] = array("name" => "Charlie", "address" => "123 main", "phone" => "000-000-0000",
"children" => $aChildren);
$aFullArray[] = array("name" => "Danny", "address" => "123 main", "phone" => "000-000-0000");
function renderTest2(array $data)
{
$html = '<ul>';
foreach ($data as $item) {
$html .= '<li>';
if (array_key_exists('children', $item)) {
$html .= $item['name'];
$html .= renderTest2($item['children']);
} else {
$html .= $item['name'] . "<input type='text' value=''> <br/>";
}
$html .= '</li>';
}
$html .= '</ul>';
return $html;
}
you are looping two times which is not required and if it has children pass children array only
Explanation:
Loop through an array and if it has children key do recursion
If not found generate li element
Looking at the code i saw the following mistake:
foreach() do foreach() so a multiple foreach() loop would be the mistake you've made.
try this code:
by calling foreach() only once and using
if (array_key_exists('children', $item)) {
$html .= $item['name'];
$html .= renderTest2($item['children']);
}
together in one foreach() the double loop isn't needed and recursion is avoided
The full code then would be:
<?php
$aFullArray = array();
$aFullArray[] = array("name" => "Adam", "address" => "123 main", "phone" => "000-000-0000");
$aFullArray[] = array("name" => "Beth", "address" => "123 main", "phone" => "000-000-0000");
$aChildren = array();
$aChildren [] = array("name" => "Mike", "address" => "123 main", "phone" => "000-000-0000");
$aChildren[] = array("name" => "Nancy", "address" => "123 main", "phone" => "000-000-0000");
$subChild = array();
$subChild [] = array("name" => "Peter", "address" => "123 main", "phone" => "000-000-0000");
$subChild [] = array("name" => "Paul", "address" => "123 main", "phone" => "000-000-0000");
$aChildren [] = array("name" => "Oscar", "address" => "123 main", "phone" => "000-000-0000",
"children" => $subChild);
$aFullArray[] = array("name" => "Charlie", "address" => "123 main", "phone" => "000-000-0000",
"children" => $aChildren);
$aFullArray[] = array("name" => "Danny", "address" => "123 main", "phone" => "000-000-0000");
function renderTest2(array $data)
{
$html = '<ul>';
foreach ($data as $item) {
$html .= '<li>';
if (array_key_exists('children', $item)) {
$html .= $item['name'];
$html .= renderTest2($item['children']);
} else {
$html .= $item['name'] . "<input type='text' value=''> <br/>";
}
$html .= '</li>';
}
$html .= '</ul>';
return $html;
}
echo renderTest2($aFullArray);
Hope this helps!
As the original code was not making use of various elements within the source arrays I simplified for testing porpoises. Hopefully the following makes sense, it seems to generate the list in the desired manner.
$html = $family = $children_family_1 = $children_family_2 = array();
$family[] = array("name" => "Adam");
$family[] = array("name" => "Beth");
$family[] = array("name" => "Danny");
$children_family_2[] = array("name" => "Peter");
$children_family_2[] = array("name" => "Paul");
$children_family_1[] = array("name" => "Mike");
$children_family_1[] = array("name" => "Nancy");
$children_family_1[] = array("name" => "Oscar", "children" => $children_family_2 );
$family[] = array("name" => "Charlie", "children" => $children_family_1 );
function familytree( $input=array(),&$html ){
$html[]='<ul>';
foreach( $input as $index => $arr ){
if( array_key_exists( 'children', $arr ) && is_array( $arr['children'] ) ){
$html[]="<li>Parent: {$arr['name']}</li>";
$html[]="<li>";
/* recurse array to repeat structure */
familytree( $arr['children'], &$html );
$html[]="</li>";
} else {
$html[]="<li><input type='text' name='name[]' value='{$arr['name']}' /></li>";
}
}
$html[]='</ul>';
return implode( PHP_EOL, $html );
}
echo familytree( $family, $html );
The generated html:
<ul>
<li><input type="text" name="name[]" value="Adam"></li>
<li><input type="text" name="name[]" value="Beth"></li>
<li><input type="text" name="name[]" value="Danny"></li>
<li>Parent: Charlie</li>
<li>
<ul>
<li><input type="text" name="name[]" value="Mike"></li>
<li><input type="text" name="name[]" value="Nancy"></li>
<li>Parent: Oscar</li>
<li>
<ul>
<li><input type="text" name="name[]" value="Peter"></li>
<li><input type="text" name="name[]" value="Paul"></li>
</ul>
</li>
</ul>
</li>
</ul>

How i can print Arrays with for each loop

<?php
$students = array(
"student1" => array(
"age" => 36,
"gender" => "male",
"qualification" => "Master",
),
"student2" => array(
"age" => 25,
"gender" => "male",
"qualification" => "BA",
),
"student3" => array(
"age" => 26,
"gender" => "male",
"qualification" => "BA",
),
"student4" => array(
"age" => 25,
"gender" => "male",
"qualification" => "BA",
),
"student5" => array(
"age" => 20,
"gender" => "male",
"qualification" => "Master",
),
"student6" => array(
"age" => 20,
"gender" => "male",
"qualification" => "F.A",
),
);
?>
And i need result like this.
Hello Student1
Your age is 36 and
Your gender is male and
Your qualification is Master.
Hello Student2
Your age is 25 and
Your gender is male and
Your qualification is BA.
I have try like this.
foreach($students as $key=>$value)
{
echo "Mr".$key."<br />";
foreach($value as $key=>$value)
{
echo" Your $key is $value and <br />";
}
}
And my result like this.
Hello Student1
Your age is 36 and
Your gender is male and
Your qualification is Master and
Hello Student2
Your age is 25 and
Your gender is male and
Your qualification is BA and
No need for that other foreach inside, you can just use one. Each copy of the sub array ($info), you will just have to call its indices.
foreach ($students as $name => $info) {
echo "
Hello $name, <br/>
Your age is: $info[age] <br/>
Your gender is: $info[gender] <br/>
Your qualification is: $info[qualification] <hr/>
";
}
But if you really want to go that two foreach route, yes you could add a condition in the second loop to prevent it from adding the superfluous and:
foreach ($students as $name => $info) {
echo "Hello $name ";
foreach($info as $att => $val) {
echo "Your $att is: $val ", (end($info) != $val) ? ' and ' : '<br/>';
}
}
Try with -
foreach($students as $key=>$value)
{
echo "Mr".$key."";
$count = 1;
foreach($value as $key=>$val)
{
echo" Your $key is $val";
if ($count != count($val)) {
echo " and ";
}
}
}
Try this code:
foreach($students as $key => $value) {
echo 'Hello ', $key, ' Your age is ', $value['age'], ' gender is ' . $value['gender'], ' and Your qualification is ', $value['qualification']
}
You can concat string with echo, but coma will be better for performance.

Empty arrays error

i have a set of php arrays, and i am trying to retrieve those details and echo. however i get errors such as Warning: Invalid argument supplied for foreach().
how can i rectify such errors from appearing?
this problem occurs when i echo all cakes from all users.
I have tried so far to eliminate possible errors from the code and also used validation statements such as if empty then do this, however the problem still persists.
<?php
//USERS ARRAYS
$users = array();
$users["john"] = array(
"first name" => "John",
"last name" => "Smith",
"address" => "London");
$users["jade"] = array(
"first name" => "Jade",
"last name" => "Anthony",
"address" => "Essex");
$users["clement"] = array(
"first name" => "Clement",
"last name" => "Smith",
"address" => "Essex");
//CAKES ARRAY
$cakes = array();
$cakes = array(
"john" => array(
"Chocolate Cake" => array(
"ingredients" => "chocolate, flour, eggs",
"cooking time" => "20 minutes"),
),
"jade" => array(
"Lemon Cheesecake" => array(
"ingredients" => "lemons, flour, eggs",
"cooking time" => "30 minutes")),
"clement" => NULL,
);
?>
<?php $user_name = 'john';?>
<h1>Name</h1>
<p><?php echo $users["first name"]; ?></p>
<h1>Cakes Made</h1>
<?php
foreach($cakes[$user_name] as $key => $val)
{ echo $key . " <strong>Ingredients: </strong>" . $val["ingredients"] . "<br>"; }
?>
<h1>All cakes from all users</h1>
<?php foreach($cakes as $cake) { ?>
<?php if(is_array($cake)) {
foreach($cake as $cakemade => $newval)
if(empty($cakemade)) { echo "";} else
{ echo $cakemade . "<strong>" . $newval['ingredients'] ."</strong> <br>"; }
?>
<?php }} ?>
your input is welcome. :)
edit: Just to be clear the code error relates to the second part of the code in which it displays all cakes from all users.
You can test if the variable in want use in foreach is set
if(isset($cakes[$user_name]) && count($cakes[$user_name]) > 0)
foreach($cakes[$user_name] as $key => $val) {}
Missing "s for the keys.Your array should be -
$cakes = array(
"john" => array(
"Chocolate Cake" => array(
"ingredients" => "chocolate, flour, eggs",
"cooking time" => "20 minutes"),
)
"jade" => array(
"Lemon Cheesecake" => array(
"ingredients" => "lemons, flour, eggs",
"cooking time" => "30 minutes"),
"clement" => NULL,
);
if(is_array($variable) && count($variable) > 0) {
foreach($variable as $key => $value) {
//Your code
}
)
You have many syntax errors in your pasted code. also use is_array() to check an array.
also you have defined $username = "john" and passing in foreach with $user_name
try
<?php
//USERS ARRAYS
$users = array();
$users["john"] = array(
"first name" => "John",
"last name" => "Smith",
"address" => "London");
$users["jade"] = array(
"first name" => "Jade",
"last name" => "Anthony",
"address" => "Essex");
$users["clement"] = array(
"first name" => "Clement",
"last name" => "Smith",
"address" => "Essex");
//CAKES ARRAY
$cakes = array();
$cakes = array(
"john" => array(
"Chocolate Cake" => array(
"ingredients" => "chocolate, flour, eggs",
"cooking time" => "20 minutes"),
),
"jade" => array(
"Lemon Cheesecake" => array(
"ingredients" => "lemons, flour, eggs",
"cooking time" => "30 minutes")),
"clement" => NULL,
);
?>
<?php $user_name = 'john';?>
<h1>Name</h1>
<p><?php echo $users["first name"]; ?></p>
<h1>Cakes Made</h1>
<?php
foreach($cakes[$user_name] as $key => $val)
{ echo $key . " <strong>Ingredients: </strong>" . $val["ingredients"] . "<br>"; }
?>
<h1>All cakes from all users</h1>
<?php foreach($cakes as $cake) { ?>
<?php if(is_array($cake)) {
foreach($cake as $cakemade => $newval)
if(empty($cakemade)) { echo "";} else
{ echo $cakemade . "<strong>" . $newval['ingredients'] ."</strong> <br>"; }
?>
<?php }} ?>
Probably the best way would be to check if the variable is an array and then check if it's empty.
As you have made clear if the variable is array and it's not empty, then you should waste processor time to iterate over an array.
So the code would look like this:
if(!empty($var) && is_array($var)) {
foreach($var as $key => $value) {
echo $key . ' => ' . $value;
}
}

php foreach loop from multidimensional array

I have a multidimensional array which I want to display in a foreach loop. I've been looking at lots of tutorials but I haven't been able to make it work yet.
This is my array and foreach loop:
$events = array(
array( Name => "First Event",
Date => "12/13/14",
Time => "12:13"
Description => "event description"
),
array( Name => "Second Event",
Date => "12/13/14",
Time => "12:13",
Description => "event description"
),
array( Name => "Third Event",
Date => "12/13/14",
Time => "12:13"
Description => "event description"
)
);
foreach($events as $event) {
echo "<div class=\"event\"><strong>";
echo $event[Name];
echo "</strong><em>";
echo $event[Date] . " at " . $event[Time];
echo "</em><div>";
echo $event[Description];
echo "</div></div>";
}
and here is how I want it to display:
<div class="event">
<strong>Event Name</strong><em>Date at Time</em>
<div>
Description
</div>
</div>
I would appreciate any help you could give. Thanks!
The keys are missing quotes and Time => "12:13" missing comma "," at the end:
<?php
$events = array(
array( "Name" => "First Event",
"Date" => "12/13/14",
"Time" => "12:13",
"Description" => "event description"
),
array( "Name" => "Second Event",
"Date" => "12/13/14",
"Time" => "12:13",
"Description" => "event description"
),
array( "Name" => "Third Event",
"Date" => "12/13/14",
"Time" => "12:13",
"Description" => "event description"
)
);
foreach($events as $event) {
?>
<div class="event">
<strong><?php echo $event["Name"];?></strong><em><?php echo $event["Date"];?></em>
<div><?php echo $event["Description"];?></div>
</div>
<?php
}
?>
Output
First Event 12/13/14
event description
Second Event 12/13/14
event description
Third Event 12/13/14
event description
The keys should be in quotes. E.g.: 'Name' rather than Name
<?php foreach($events as $event): ?>
<div class="event">
<strong><?php echo $event['Name'] ?></strong><em><?php echo $event['Date'] ?> at <?php echo $event['Time'] ?></em>
<div>
<?php echo $event['Description'] ?>
</div>
</div>
<?php endforeach; ?>
Try this:
foreach($events as $record) {
$name = $record["name"];
$date = $record["date"];
$time = $record["time"];
$description = $record["description"];
print("
// your html code with the variables here
");
}

Categories