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
");
}
Related
The loop below outputs from the $defaultValues values, there are 2 nested arrays in this array which are "colors" and "lessons".
This loop also takes the substring values from the $search array and replaces them with the values from the $replace.
Question: How to replace nested array clause value "colors" and "lessons" from $defaultValues
values: "colors"=>["4", "5", "6"] and "lessons" =>["7 " , " 8", "9"] from $replace"
I can't figure out how to do this, my current code outputs this:
Name: 1
Age: 2
Whe are u from: 3
Your favorite color: 4
Choose courses: 7
Your comment: 10
I would like the code to output this:
Name: 1
Age: 2
Whe are u from: 3
Your favorite color: 4,5,6
Choose courses: 7,8,9
Your comment: 10
$defaultValues = [
"name" => "Name: <div class='user'> write your name </div>",
"age" => "Age: <div class='age'> enter your age </div>",
"from" => "Whe are u from: <div class='from'> write where are you from </div>",
"colors" => ["Your favorite color: <div class='colors'> you didn't say your favorite color </div>"],
"lessons" => ["Choose courses: <div class='lessons'> you have not chosen any course </div>"],
"comment" => "Your comment: <div class='comment'> no comments </div>",
];
$search = [
"name" => "write your name",
"age" => "enter your age",
"from" => "write where are you from",
"colors" => ["you didn't say your favorite color"],
"lessons" => ["you have not chosen any course"],
"comment" => "no comments",
];
$replace = [
"name" => "1",
"age" => "2",
"from" => "3",
"colors" => ["4", "5", "6"],
"lessons" => ["7", "8", "9"],
"comment" => "10",
];
foreach($defaultValues as $key => $items){
echo "<div class='block'>";
if(is_array($items)){
foreach($items as $child){
$items = str_replace($search[$key], $replace[$key], $child);
}
}
echo $items = str_replace($search[$key], $replace[$key], $items);
echo "</div>";
}
If you meant to join the array of colors and lessons to create the string to replace the corresponding placeholders you may use the function implode
https://www.php.net/manual/en/function.implode.php
Here's the code fragment:
if(is_array($items)){
foreach($items as $child){
$replaceListImploded = implode(",", $replace[$key]);
$items = str_replace($search[$key], $replaceListImploded, $child);
}
}
The corresponding output:
<div class='block'>
Your favorite color: <div class='colors'> 4,5,6 </div>
</div>
<div class='block'>
Choose courses: <div class='lessons'> 7,8,9 </div>
</div>
Here's the whole snippet: https://onlinephp.io/c/098a6
You just need to use implode to parse the array into a comma-separated string for output!
<?php
// example code
$defaultValues = [
"name" => "Name: <div class='user'> write your name </div>",
"age" => "Age: <div class='age'> enter your age </div>",
"from" => "Whe are u from: <div class='from'> write where are you from </div>",
"colors" => ["Your favorite color: <div class='colors'> you didn't say your favorite color </div>"],
"lessons" => ["Choose courses: <div class='lessons'> you have not chosen any course </div>"],
"comment" => "Your comment: <div class='comment'> no comments </div>",
];
$search = [
"name" => "write your name",
"age" => "enter your age",
"from" => "write where are you from",
"colors" => ["you didn't say your favorite color"],
"lessons" => ["you have not chosen any course"],
"comment" => "no comments",
];
$replace = [
"name" => "1",
"age" => "2",
"from" => "3",
"colors" => ["4", "5", "6"],
"lessons" => ["7", "8", "9"],
"comment" => "10",
];
foreach($defaultValues as $key => $items){
echo "<div class='block'>";
$replace_item = (is_array($replace[$key]) ? implode(",", $replace[$key]) : $replace[$key]);
if(is_array($items)){
foreach($items as $child){
$items = str_replace($search[$key], $replace_item, $child);
}
}
echo $items = str_replace($search[$key], $replace_item, $items);
echo "</div>";
}
echo $items = is_array($search[$key]) ? implode(',', $replace[$key]) : str_replace($search[$key], $replace[$key], $items);
will output you looking for
Here i have two arrays 1.response 2.selected_amenties,in first array value i displayed in checkbox, now i want to make checked values for Swimming Pool and Power Backup because of this values equal to the first array (response ), how can do this ?
<?php
$response = Array
(
Array
(
"id" => "57e2340eaebce1023152759b",
"name" => "Squash Court",
"amenityType" => "Sports"
),
Array
(
"id" => "57e23470aebce1023152759d",
"name" => "Swimming Pool",
"amenityType" => "Sports"
),
Array
(
"id" => "57e2347caebce1023152759e",
"name" => "Power Backup",
"amenityType" => "Convenience"
),
Array
(
"id" => "57e23486aebce1023152759f",
"name" => "Day Care Center",
"amenityType" => "Convenience"
)
);
$selected_amenties = Array( "0" => "Swimming Pool",
"1" => "Power Backup"
);
foreach($response as $amenity)
{
?>
<div class="checkbox">
<input type="checkbox" class="aminit" name="aminit" value="<?php echo $amenity['name']?>"><?php echo $amenity['name']?>
</div>
<?php
}
?>
Try like this:
<?php
foreach($response as $amenity)
{
$checked = in_array($amenity['name'], $selected_amenties) ? 'checked' : '';
?>
<div class="checkbox">
<input type="checkbox" class="aminit" name="aminit" value="<?php echo $amenity['name'] ?>" <?php echo $checked; ?>><?php echo $amenity['name']?>
</div>
<?php
}
?>
$selected_amenties = array('Swimming Pool', 'Power Backup');
foreach($response as $amenity) {
$check = '';
in_array($amenity, $selected_amenties) and $check = ' checked="checked" ';
echo '<div class="checkbox">';
echo '<input type="checkbox" ' . $check . ' class="aminit" name="aminit" value="<?php echo $amenity['name']?>"><?php echo $amenity['name']?>';
echo '</div>';
}
I want to fill an array in a while loop.
I want to display this array like this :
category 1 => Company A => 'name', 'city', 'CEO',
Company B => 'name', 'city', 'CEO'
category 2 = Company A => 'name', 'city', 'CEO',
Company B => 'name', 'city', 'CEO'
ect ........
Here's my current code in my while loop
$array_cat[] = array(
array(
'category' => $cat,
array(
'company' => array(
'name' => $name,
'city' => $city,
'CEO' => $ceo
)
)
)
);
My code WHen I display it
foreach ($array_cat as $item) {
foreach ($array_cat['category'] as $company_display) {
echo $company_display['company']['name'][];
}
}
Thanks for the help ;)
try this:
$array1 = array('category1' =>
array('Company A' =>
array('name', 'city', 'CEO')),
'category2' =>
array('Company B' =>
array('name', 'city', 'CEO')));
foreach ($array1 as $key => $value)
{
foreach ($value as $key1 => $value1)
{
echo "<pre>";
print_r($value1);
echo "</pre>";
}
}
Problem is in your inner foreach loop
There is a problem in inner foreach loop and echo line.
Replace $array_cat by $item and in echo line there is an error:
Cannot use [ ] for reading
By following way, you can achieve your goal.
foreach ($array_cat as $item) {
foreach ($item as $company_display) {
echo $company_display['category']['company']['name'];
}
}
How to create this multidimensional array in PHP
If I would design an array for that, i would do something like this:
$array = array(
//Category 1, nameless i assume?
array(
//Companies
"Company A" => array(
//Company properties
"name" => "My A company",
"city" => "Some city that starts with an A",
"CEO" => "Some CEO that starts with an A"
),
"Company B" => array(
//Company properties
"name" => "My B company",
"city" => "Some city that starts with an B",
"CEO" => "Some CEO that starts with an B"
),
),
//Category two, nameless i assume
array(
//Companies
"Company C" => array(
//Company properties
"name" => "My C company",
"city" => "Some city that starts with an C",
"CEO" => "Some CEO that starts with an C"
),
"Company D" => array(
//Company properties
"name" => "My D company",
"city" => "Some city that starts with an D",
"CEO" => "Some CEO that starts with an D"
),
),
);
Then, if i wanted to get some data out of it, i could do something like this:
$companyAcity = $array[0]['Company A']['city'];
echo $companyAcity;
If I wanted to loop in the array, i could so something like this:
for($categoryID = 0; categoryID < count($array); $i++) {
//Prints data for each category it loops through.
echo $array[$categoryID];
//Loops through the companies contained in the current category where it's looping through
foreach($array[$categoryID] as $companyName => $companyData) {
echo $companyName;
echo $companyData['name'];
}
}
I want to fill an array in a while loop.
If you want to add data to the array while looping in it, you can do something like this:
for($categoryID = 0; categoryID < count($array); $i++) {
$array[$categoryID][] = $categoryID +1;
}
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>";
}
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;
}
}