I have a directory of files who's main purpose is to store php variables for inclusion into other files in the site. Each file contains the same set of variables, but with different values.
for example:
event1.php
<?php
$eventActive = 'true';
$eventName = My First Event;
$eventDate = 01/15;
?>
event2.php
<?php
$eventActive = 'true';
$eventName = My Second Event;
$eventDate = 02/15;
?>
In addition to calling these variables in other pages, I want to create a page that contains a dynamic list, based on the variables stored in each file within the directory.
Something like (basic concept):
for each file in directory ('/events') {
if $eventActive = 'true'{
<p><? echo $eventName ?></p>
}
}
What is the best way to do this?
Create an Event
class or an array
of each event. Then populate it from the directory.
$index = 0;
foreach (array_filter(glob($dir.'/*'), 'is_file') as $file) {
@include $file; // Parses the file, so the variables within are set.
$events[$index]['active'] = $eventActive;
$events[$index]['name'] = $eventName;
$events[$index]['date'] = $evetnDate;
$index++;
// OR
// $events[] = new Event($eventName, $eventDate, $eventActive);
}
// Now the $events array contains all your events.
// List out the active ones
foreach ($events as $event) {
echo ($event['active'] === 'true') ? $event['name'] : '';
// OR
// echo $event->isActive() ? $event->getName() : '';
}
Ok, so I spend some time with it and was able to reslove the issue with a cleaner solution, but utilizing an external json file to store the values
<?php
$json = file_get_contents('events.json');
$jsonArray = json_decode($json, true); // decode the JSON into an associative array
foreach ($jsonArray as $value) {
if (($value['active'] === 't') && ($value['fromDate'] >= $currentDate)) {
echo '<p>'.$value['title'].' '.$value['fromDate'].' - '.$value['toDate'].'</p>';
}
}
echo $currentDate;
?>