Translate PHP腳本以讀取CSV檔案並傳回echo多次
P粉127901279
2023-08-06 19:24:52
<p>我已經編寫了一個用於讀取CSV檔案並根據時間和日期在網站上發布結果的廣播節目表的PHP腳本。然而,它似乎會發布兩次。 <br /><br />以下是腳本內容:</p><p><br /></p>
<pre class="brush:php;toolbar:false;"><?php
// Step 1: Replace 'data.csv' with the path to your CSV file
$csvFile = 'schedule.csv';
// Step 2: Read CSV and store its contents in an array
if (($handle = fopen($csvFile, 'r')) !== false) {
$csvData = [];
while (($data = fgetcsv($handle)) !== false) {
$csvData[] = $data;
}
fclose($handle);
} else {
die("Error opening CSV file.");
}
// Step 3: Get the current day and time
$currentDay = date('l'); // l gives the full textual representation of the day (e.g., "Monday")
$currentHour = date('H'); // H gives the hour in 24-hour format (e.g., "13" for 1 PM)
// Adjust hour offset below.
$Hour = $currentHour 1;
// Step 4: Filter the array based on the current day and time
$filteredData = [];
foreach ($csvData as $row) {
// Assuming that your CSV file has a "Day" column and a "Time" column
$day = $row[0];
$time = intval($row[1]);
$program_name= $row[2];
$program_when= $row[2];
$program_img= $row[4];
// Check if the row matches the current day and time
if ($day === $currentDay && $Hour >= $time) {
$filteredData[] = $row;
}
}
// Step 5: Display the filtered data with CSS classes for each row
if (count($filteredData) > 0) {
foreach ($filteredData as $row) {
echo "<div class='row'>";
echo "<div class='col-5'>";
echo "<img src='$row[4]' width='90' height='90' border='0'>";
echo "</div>";
echo "<div class='col-7'>";
echo "<h3>$row[2]<br>$row[3]</h3>";
echo "</div>";
echo "</div>";
}
} else {
echo 'Not available.';
}</pre>
<p>這是我在CSV檔案中測試的資料:</p>
<pre class="brush:php;toolbar:false;">Friday,12,MMV,until 1pm,top_mmv.png
Friday,13,MMV,until 2pm,top_mmv.png
Friday,14,MMV,until 3pm,top_mmv.png
Friday,15,MMV,until 4pm,top_mmv.png</pre>
<p>但當到達週五下午2點時,它會同時發布1點和2點的行。請問我做錯了什麼? </p>
你需要指定收集資料的條件,
例如,現在的目前時間是14點(加1小時是你的調整)。
$Hour >= $time
#我認為你可以看到問題出在哪裡。