Distinct in foreach loop. To many result because of two loops - php

I've a custom system that provides adding new information in custom columns.
I've two tables in my database. One for my value data and the second for the columns (data fieds).
Above you see a image from my form that is build by custom data fields with data per field.
Only in my for each i get for every data a extra loop so that is why i got from every data field two. How can I fix this?
<?php foreach ($list as $key => $value) { ?>
<?php foreach ($dataList as $data) { ?>
<div class="row clearfix">
<div class="col-xl-12">
<div class="form-group form-group-default">
<label><?php echo ucfirst($key); ?></label>
<?php if($key == $data['name']) { ?>
<input type="text" class="form-control" name="value_<?php echo trim($data['name']); ?>" value="<?php echo trim($data['value']); ?>" required>
<?php }else{ ?>
<input type="text" class="form-control" name="value_<?php echo trim($data['name']); ?>" placeholder="<?php echo ucfirst($key); ?>">
<?php } ?>
</div>
</div>
</div>
<?php } ?>
<?php } ?>
$list you'll find a list of data fields and in $dataList you'll find records of data.
Database structure:
data:
['id','hash','field_id','value']
Example of data:
['id' => 1, 'hash' => 123, 'field_id' => 1, 'value' => 'food']
Fields:
['id','name']
Example of fields:
['id' => 1, 'name' => 'firstname']
Below you'll find the foreach variables:
$data = processing('read', 'data JOIN fields ON data.field_id = fields.id', ['data.value,data.uid,fields.name,data.id,fields.category_id'], 'uid = "' . trim($_GET['datalist']) . '"', true);
$dataItem = processing('read', 'data JOIN fields ON data.field_id = fields.id', ['fields.category_id'], 'uid = "' . trim($_GET['datalist']) . '"');
$fieldList = processing('read', 'fields', ['name'], 'category_id = "'. trim($dataItem['category_id']) . '"',true);
$list = [];
foreach($fieldList as $key => $value) {
$list[$value['name']] = $value['name'];
}
Update:
I've update my own question because the other answers didn't resolved my problem. The only problem on my answer is, that when I update it doesnt look at the id of the item but at the name, so i can't save two items with the same name.
<?php foreach ($dataItems as $key => $value) { ?>
<div class="row clearfix">
<div class="col-xl-12">
<div class="form-group form-group-default">
<label><?php echo ucfirst($key); ?></label>
<input type="text" placeholder="<?php echo ucfirst($key); ?>" class="form-control" name="<?php echo trim($key); ?>" value="<?php echo trim($value); ?>">
</div>
</div>
</div>
<?php } ?>
method:
public function getDataListItems(int $category, array $list) {
global $dbh;
$query = 'SELECT data.value, data.uid, fields.name FROM data JOIN fields ON data.field_id = fields.id WHERE fields.category_id = "' . trim($category) . '" ORDER BY uid';
$sql = $dbh->prepare($query);
$sql->execute();
$values = $sql->fetchAll(PDO::FETCH_ASSOC);
foreach ($values as $row) {
if (!isset($items[$row['uid']])) {
$items[$row['uid']] = array_fill_keys($list, ''); // if it needs to dynamically generated
$items[$row['uid']]['uid'] = $row['uid'];
}
$items[$row['uid']][$row['name']] = $row['value'];
}
return $items;
}
Return:
array (
'7d1f4f8e906245f' =>
array (
'Voornaam' => 'Bettina',
'Achternaam' => 'Les',
'Initialen' => 'pop',
'uid' => '7d1f4f8e906245f',
),
'7d1f4f8e906245g' =>
array (
'Voornaam' => 'Simone',
'Achternaam' => '',
'Initialen' => '',
'uid' => '7d1f4f8e906245g',
),
'7d1f4f8e906245l' =>
array (
'Voornaam' => 'test',
'Achternaam' => 'Kül',
'Initialen' => 'lol',
'uid' => '7d1f4f8e906245l',
),
'7d1f4f8e906245s' =>
array (
'Voornaam' => 'Joshua',
'Achternaam' => 'Mas',
'Initialen' => '',
'uid' => '7d1f4f8e906245s',
),
'gGcYEJdRYJ1vqcn' =>
array (
'Voornaam' => '',
'Achternaam' => 'Hello',
'Initialen' => '',
'uid' => 'gGcYEJdRYJ1vqcn',
),
)

Related

PHP SQL Sorting information into HTML div elements

I am trying to sort SQL results into different divs based on the category they are assigned in the database. There are four categories and it works fine as long as there are videos available for all 4 categories. It will create 1 div for each and assign the videos to the correct div. The issue I'm having is that I'd like to also create the div even if there are no videos available within that category. (Pretty new so the code is probably pretty chunky for what it should be)
PHP code
$stmt = $conn->prepare("SELECT * FROM VIDEOS WHERE categorie=:category ORDER BY categorie ASC, subcategorie ASC");
$stmt->bindParam(':category', $_POST['category']);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "<div class='spacer'>";
$testcase = "";
for($x = 0; $x < sizeof($result); $x++) {
if($result[$x]["subcategorie"] != $testcase) {
echo
"</div><div class='subcategory_container active' id='" . $result[$x]["subcategorie"] . "'>
<h3 class='subcategory_title'>". $result[$x]["subcategorie"] . "</h3>";
echo
"<div class='video_div'> <iframe width='196' height='350'
src='" . $result[$x]['linkembed'] . "'>
</iframe></div>";
$testcase = $result[$x]["subcategorie"];
} else {
echo
"<div class='video_div'> <iframe width='196' height='350'
src='" . $result[$x]['linkembed'] . "'>
</iframe></div>";
}
}
I have tried adding multiple if($result[$x]["subcategorie"] == "categoryname") statements but specifying the name within a for loop resulted in there being multiple of the same divs and a repeat of data. So far I've tried to look up SQL group by PHP tutorials but they all show the same result being inside of a table. The goal is to get the information into their own div with the ID of said div being the category name. I'm working with AJAX calls using JS to fix the issue won't work.
This solution builds a $videos array using the static subcategories as keys, it then populates these after looking through the database, then it's a matter of echoing the iframes if records exist.
<?php
/*
Question Author: Terhert
Question Answerer: Jacob Mulquin
Question: PHP SQL Sorting information into HTML div elements
URL: https://stackoverflow.com/questions/74715867/php-sql-sorting-information-into-html-div-elements
Tags: php, mysql
*/
include '../../inc/helpers.php';
try {
$pdo = new PDO(DB_DSN, DB_USER, DB_PASS, DB_OPTIONS);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
$pdo->query('DROP TABLE table74715867;');
$pdo->query('CREATE TABLE IF NOT EXISTS table74715867 (id TEXT, name TEXT, linkembed TEXT, categorie TEXT, subcategorie TEXT);');
$data = [
['id' => '1', 'name' => 'test1','linkembed' => 'http://example.org', 'categorie' => 'abc', 'subcategorie' => 'kracht'],
['id' => '2', 'name' => 'test2','linkembed' => 'http://example.org', 'categorie' => 'abc', 'subcategorie' => 'uithouding'],
['id' => '9', 'name' => 'test9','linkembed' => 'http://example.org', 'categorie' => 'abc', 'subcategorie' => 'mobiliteit'],
['id' => '10', 'name' => 'test10','linkembed' => 'http://example.org', 'categorie' => 'abc', 'subcategorie' => 'mobiliteit'],
['id' => '3', 'name' => 'test3','linkembed' => 'http://example.org', 'categorie' => 'xyz', 'subcategorie' => 'majig1'],
['id' => '4', 'name' => 'test4','linkembed' => 'http://example.org', 'categorie' => 'xyz', 'subcategorie' => 'majig2'],
['id' => '5', 'name' => 'test5', 'linkembed' => 'http://example.org', 'categorie' => '123', 'subcategorie' => 'whatchmacallit1'],
['id' => '6', 'name' => 'test6', 'linkembed' => 'http://example.org', 'categorie' => '123', 'subcategorie' => 'whatchmacallit2'],
['id' => '7', 'name' => 'test7', 'linkembed' => 'http://example.org', 'categorie' => 'qwerty', 'subcategorie' => 'fizz1'],
['id' => '8', 'name' => 'test8', 'linkembed' => 'http://example.org', 'categorie' => 'qwerty', 'subcategorie' => 'buzz1'],
];
$stmt = $pdo->prepare('INSERT INTO table74715867 SET id=:id, name=:name, linkembed=:linkembed, categorie=:categorie, subcategorie=:subcategorie;');
foreach ($data as $record) {
$stmt->execute([
':id' => $record['id'],
':name' => $record['name'],
':linkembed' => $record['linkembed'],
':categorie' => $record['categorie'],
':subcategorie' => $record['subcategorie']
]);
}
$category = 'abc';
$stmt = $pdo->prepare("SELECT * FROM table74715867 WHERE categorie=:category ORDER BY categorie ASC, subcategorie ASC");
$stmt->bindParam(':category', $category);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$videos = ["kracht" => [], "uithouding" => [], "mobiliteit" => [], "stretching" => []];
foreach ($result as $record) {
$videos[$record['subcategorie']][] = $record;
}
foreach ($videos as $subcategory => $records) {
echo '<div class="subcategory_container active" id="' . $subcategory . '">' .
'<h3 class="subcategory_title">' . $subcategory . '</h3>';
if (!empty($records)) {
foreach ($records as $record) {
echo '<div class="video_div"><iframe width="196" height="350" src="'.$record['linkembed'].'"></iframe></div>';
}
}
echo '</div>';
}
Here's the resulting HTML:
<head></head>
<body>
<div class="subcategory_container active" id="kracht">
<h3 class="subcategory_title">kracht</h3>
<div class="video_div">
<iframe src="http://example.org" width="196" height="350"></iframe>
</div>
</div>
<div class="subcategory_container active" id="uithouding">
<h3 class="subcategory_title">uithouding</h3>
<div class="video_div">
<iframe src="http://example.org" width="196" height="350"></iframe>
</div>
</div>
<div class="subcategory_container active" id="mobiliteit">
<h3 class="subcategory_title">mobiliteit</h3>
<div class="video_div">
<iframe src="http://example.org" width="196" height="350"></iframe>
</div>
<div class="video_div">
<iframe src="http://example.org" width="196" height="350"></iframe>
</div>
</div>
<div class="subcategory_container active" id="stretching">
<h3 class="subcategory_title">stretching</h3>
</div>
</body>

Display the member of one array depending on the other array

i have an array i and i want to show the array values if the name of same array repeat in the another array and have true value
my arrays like this
$array1 = [
array(
'name' => internal_evidence
'price' => 30
'course_id' => 3
),
array(
'name' => international_evidence
'price' => 450
'course_id' => 3
),
array(
'name' => internal_evidence
'price' => 10
'course_id' => 1
),
array(
'name' => technical_evidence
'price' => 134
'course_id' => 3
),
];
$array2 = [
array(
'id' => 3
'name' => graphic
'price' => 150
'attr' => array(
'internal_evidence' => 'true',
'international_evidence' => 'false',
'technical_evidence' => 'true'
)
),
array(
'id' => 5
'name' => 3dmax
'price' => 300
'attr' => array(
)
),
array(
'id' => 1
'name' => ICDL
'price' => 480
'attr' => array(
'internal_evidence' => 'true',
)
),
];
i want to showing this all attr selected with true value in like this
also I want to sum price of array2 member and array1
<h2>graphic</h2>
<p>internal_evidence</p>
<p>technical_evidence</p>
<small>course price: 150</small>
<small>314</small> <!-- Price with selected evidence -->
<h2>3dmax</h2>
<small>course price: 300</small>
<!-- its not have attr evidence -->
<h2>ICDL</h2>
<p>internal_evidence</p>
<small>course price: 480</small>
<small>490</small> <!-- Price with selected evidence -->
i try this but its don`t work properly
$priceOfAttr = 0;
foreach($array2 as $key => $cat):
echo "<h2>{$cat['name']}</h2>";
foreach($array1 as $pr):
if($pr['course_id'] == $cat['id']):
foreach($cat['attr'] as $m => $optionV):
if($m == $pr['name'] && $optionV == "true"){
echo $m .'<br>';
$priceOfAttr += $pr['price'];
// echo "<small>{$cat['price']}</small><br>";
// echo $cat['price'] + $pr['price']. "<br>";
}
endforeach;
echo $priceOfAttr + $cat['price'] . '<br>';
endif;
endforeach;
echo '<br>';
endforeach;
I'd use a combination array_reduce and array_map to transform your data into what you need, then simply loop over that to display your view:
<?php
// Index your $array1 by [id][name]
$array1ByIdAndName = array_reduce($array1, static function ($byIdAndName, $entry) {
$byIdAndName[$entry['course_id']][$entry['name']] = $entry;
return $byIdAndName;
});
// Transform $array2's `attr` entries into attribute list + compute total price
$array2 = array_map(static function ($entry) use ($array1ByIdAndName) {
$entry['total_price'] = $entry['price'];
$entry['attr'] = array_reduce(array_keys($entry['attr']), static function ($attrs, $attrName) use ($array1ByIdAndName, &$entry) {
if ($entry['attr'][$attrName] === 'true') {
$attrs[] = $attrName;
$entry['total_price'] += $array1ByIdAndName[$entry['id']][$attrName]['price'];
}
return $attrs;
}, []);
return $entry;
}, $array2);
// Display your view
?>
<?php foreach ($array2 as $entry): ?>
<h2><?= $entry['name'] ?></h2>
<?php foreach ($entry['attr'] as $attrName): ?>
<p><?= $attrName ?></p>
<?php endforeach ?>
<small>course price : <?= $entry['price'] ?></small>
<?php if ($entry['total_price'] > 0): ?>
<small><?= $entry['total_price'] ?></small>
<?php endif ?>
<?php endforeach ?>
Demo: https://3v4l.org/nS3Gl

Insert_batch Error Codeigniter 3.1.4

A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Filename: database/DB_query_builder.php
Line Number: 1539
Backtrace: File: D:\xampp\htdocs\visio\application\models\projectmodel.php
Line: 56
Function: insert_batch
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Array' at line 1
INSERT INTO paymentsize () VALUES ('8'), ('2017-06-07'), ('Residential'), ('L'), ('120'), ('200'), ('10000'), ('15000'), ('30'), ('12000'), ('40'), ('1000'), ('60'), ('125000'), ('10'), ('10000'), ('15000'), ('20000'), Array
Filename: D:/xampp/htdocs/visio/system/database/DB_driver.php
Line Number: 691
My Controller is:
public function store_payment()
{
$post = array();
$post = $this->input->post(NULL,TRUE);
$count=count($this->input->post('pro_id'));
echo CI_VERSION;
for($i = 0; $i < $count; $i++){
$post []= array(
'pro_id' => $post['pro_id'][$i],
'date_add' => $post['date_add'][$i],
'category' => $post['category'][$i],
'type' => $post['type'][$i],
'size' => $post['size'][$i],
'counts' => $post['counts'][$i],
'booking' => $post['booking'][$i],
'confirmation' => $post['confirmation'][$i],
'confirm_days' => $post['confirm_days'][$i],
'allocation' => $post['allocation'][$i],
'allocate_days' => $post['allocate_days'][$i],
'm_installment' => $post['m_installment'][$i],
'month' => $post['month'][$i],
'y_instalment' => $post['y_instalment'][$i],
'halfyear' => $post['halfyear'][$i],
'leveling' => $post['leveling'][$i],
'demarcation' => $post['demarcation'][$i],
'possession' => $post['possession'][$i]
);
}
$this->projects->add_payment($post);
}
My Model is:
public function add_payment($array)
{
// echo "<pre>";
// print_r($array);
// exit();
return $this->db->insert_batch('paymentsize',$array);
}
My View is:
<tbody>
<input type="hidden" name="pro_id[]" value="<?= $project->pro_id; ?>" >
<tr>
<td width="14%">
<div class="col-lg-10">
<div class="form-group form-black label-floating is-empty">
<label class="control-label" style="margin-top: -10px;">Date</label>
<input type="date" name="date_add[]" value="<?php echo date('Y-m-d'); ?>" class="form-control" >
<span class="material-input"></span>
</div>
</div>
</td>
<td width="14%">
<div class="col-lg-10">
<div class="form-group form-black label-floating is-empty">
<label class="control-label">Plot Category</label>
<select name="category[]" class="form-control">
<option> </option>
<option>Residential</option>
<option>Commercial</option>
</select>
<span class="material-input"></span>
</div>
</div>
</td>
<td>
if i use print_r it shows all array elements with respective Values.. but it is not inserting in DB Table..
my view has a table with 17 text fields... i just mention few for an Example...
waiting for help.... :)
Thank you in advance...
Change your controller as following code,
public function store_payment()
{
$post = array();
$post = $this->input->post(NULL,TRUE);
$count=count($this->input->post('pro_id'));
echo CI_VERSION;
for($i = 0; $i < $count; $i++){
$post = array(
'pro_id' => $post['pro_id'][$i],
'date_add' => $post['date_add'][$i],
'category' => $post['category'][$i],
'type' => $post['type'][$i],
'size' => $post['size'][$i],
'counts' => $post['counts'][$i],
'booking' => $post['booking'][$i],
'confirmation' => $post['confirmation'][$i],
'confirm_days' => $post['confirm_days'][$i],
'allocation' => $post['allocation'][$i],
'allocate_days' => $post['allocate_days'][$i],
'm_installment' => $post['m_installment'][$i],
'month' => $post['month'][$i],
'y_instalment' => $post['y_instalment'][$i],
'halfyear' => $post['halfyear'][$i],
'leveling' => $post['leveling'][$i],
'demarcation' => $post['demarcation'][$i],
'possession' => $post['possession'][$i]
);
}
$this->projects->add_payment($post);
}
You used $post for two purpose, change your controller codes as following code:
public function store_payment()
{
$post = $this->input->post(NULL,TRUE);
$count=count($this->input->post('pro_id'));
echo CI_VERSION;
$data = array();
for($i = 0; $i < $count; $i++){
$data []= array(
'pro_id' => $post['pro_id'][$i],
'date_add' => $post['date_add'][$i],
'category' => $post['category'][$i],
'type' => $post['type'][$i],
'size' => $post['size'][$i],
'counts' => $post['counts'][$i],
'booking' => $post['booking'][$i],
'confirmation' => $post['confirmation'][$i],
'confirm_days' => $post['confirm_days'][$i],
'allocation' => $post['allocation'][$i],
'allocate_days' => $post['allocate_days'][$i],
'm_installment' => $post['m_installment'][$i],
'month' => $post['month'][$i],
'y_instalment' => $post['y_instalment'][$i],
'halfyear' => $post['halfyear'][$i],
'leveling' => $post['leveling'][$i],
'demarcation' => $post['demarcation'][$i],
'possession' => $post['possession'][$i]
);
}
$this->projects->add_payment($data);
}

how to make checked checkbox in two arrays

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

Multi-Dimensional PHP array – select data from key

Not sure if I titled this question correctly. I'm having some trouble looping over a multi-demensional php array to build some HTML nodes. Here is the array I'm looping over:
$locations = array(
'CityName' => array(
array(
'title' => 'Title',
'phone' => '(555) 555-5555',
'address' => '1234 Fake st.',
'city' => 'Ventura',
'state' => 'CA',
'zip' => '93003',
'url' => 'http://www.google.com/'
),
array(
'title' => 'Title',
'phone' => '(555) 555-5555',
'address' => '1234 Fake st.',
'city' => 'Ventura',
'state' => 'CA',
'zip' => '93003',
'url' => 'http://www.google.com/'
),
),
'CityName2' => array(
array(
'title' => 'Title',
'phone' => '(555) 555-5555',
'address' => '1234 Fake st.',
'city' => 'Ventura',
'state' => 'CA',
'zip' => '93003',
'url' => 'http://www.google.com/'
),
array(
'title' => 'Title',
'phone' => '(555) 555-5555',
'address' => '1234 Fake st.',
'city' => 'Ventura',
'state' => 'CA',
'zip' => '93003',
'url' => 'http://www.google.com/'
)
)
);
Keep in mind I may have built this array incorrectly for what I'm trying to do. The HTML output for this loop should be:
<h4>CityName</h4>
<ul>
<li>
<p>Title</p>
<p>1234 Fake St.</p>
<p>Ventura, CA 93003</p>
<p>(555) 555-5555</p>
<p class="link">Visit Website</p>
</li>
<li>
<p>Title</p>
<p>1234 Fake St.</p>
<p>Ventura, CA 93003</p>
<p>(555) 555-5555</p>
<p class="link">Visit Website</p>
</li>
</ul>
<h4>CityName2</h4>
<ul>
...
</ul>
I think what I want to do is to be able to grab the individual pieces of data to plug into my HTML template.. like $location['title'], $location['phone'], etc. The PHP that I currently have will only go as far to loop over and echo out the keys or values from each individual location array.
<?php
// Printing all the keys and values one by one
$locationNames = array_keys($locations);
for($i = 0; $i < count($locations); $i++) {
echo "<h4>" . $locationNames[$i] . "</h4>";
echo "<ul>";
foreach($locations[$locationNames[$i]] as $key => $value) {
foreach($value as $key => $value) {
echo $value;
}
}
echo "</ul>";
}
?>
Use nested foreach loops amd drop the values in to the appropriate places:
<?php foreach ($locations as $location => $ldata) { ?>
<h4><?php echo $location; ?></h4>
<ul>
<?php foreach ($ldata as $attribute) { ?>
<li>
<p><?php echo $attribute['title']; ?></p>
<p><?php echo $attribute['address']; ?></p>
<p><?php echo $attribute['city'] . " ," . $attribute['state'] . " " . $attribute['zip']; ?></p>
<p><?php echo $attribute['phone']; ?></p>
<p class="link">Visit Website</p>
</li>
<? php } ?>
<?php } ?>
You just need nested (foreach) loops:
<?php foreach($locations as $cityname => $location):?>
<h4><?=$cityname?></h4>
<ul>
<?php foreach($location as $place:?>
<li>
<p><?=$place['title']?></p>
<p><?=$place['phone']?></p>
<!-- etc etc-->
</li>
<?php endforeach;?>
</ul>
<?php endforeach;?>
Something like this should work. I won't implement the HTML for you, but you it should be easy to do. This has the advantage that if you have dynamic keys in the inner array, you won't have to know them before hand.
foreach($locations as $key => $value) {
echo $key, PHP_EOL;
$data = $locations[$key];
$length = count($data);
for($i = 0; $i < $length; $i++) {
$values = $data[$i];
foreach($values as $key2 => $value2)
echo "\t", $key2, ": ", $value2, PHP_EOL;
}
}
Just a few tweaks to your code:
<?php
// Printing all the keys and values one by one
$locationNames = array_keys($locations);
for($i = 0; $i < count($locations); $i++) {
echo "<h4>" . $locationNames[$i] . "</h4>";
echo "<ul>";
foreach($locations[$locationNames[$i]] as $key => $value) {
echo "<li>"; // add list open tag <-- tweak #1
foreach($value as $key => $value) {
echo "<p>$value</p>"; // add paragraph tags <-- tweak #2
}
echo "</li>"; // add list close tag <-- tweak #3
}
echo "</ul>";
}
?>
PHP Sandbox example.

Categories