Translate PHP脚本以读取CSV文件并返回echo多次
P粉127901279
P粉127901279 2023-08-06 19:24:52
[PHP讨论组]
<p>我已经编写了一个用于读取CSV文件并根据时间和日期在网站上发布结果的广播节目表的PHP脚本。然而,它似乎会发布两次。<br /><br />以下是脚本内容:</p><p><br /></p> <pre class="brush:php;toolbar:false;">&lt;?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 &amp;&amp; $Hour &gt;= $time) { $filteredData[] = $row; } } // Step 5: Display the filtered data with CSS classes for each row if (count($filteredData) &gt; 0) { foreach ($filteredData as $row) { echo "&lt;div class='row'&gt;"; echo "&lt;div class='col-5'&gt;"; echo "&lt;img src='$row[4]' width='90' height='90' border='0'&gt;"; echo "&lt;/div&gt;"; echo "&lt;div class='col-7'&gt;"; echo "&lt;h3&gt;$row[2]&lt;br&gt;$row[3]&lt;/h3&gt;"; echo "&lt;/div&gt;"; echo "&lt;/div&gt;"; } } 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>
P粉127901279
P粉127901279

全部回复(1)
P粉481815897

你需要指定收集数据的条件,

if ($day === $currentDay && $Hour >= $time) {

例如,现在的当前时间是14点(加1小时是你的调整)。

$Hour >= $time

15 >= time from first line of csv is 12 - true
15 >= time from second line of csv is 13 - true
15 >= time from third line of csv is 14 - true
15 >= 15 - true

我认为你可以看到问题出在哪里。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号