我正在尝试将csv文件转换为HTML表格。对于第一部分,我试图将csv文件中的所有时间单元格加载到时间数组中,将事件单元格加载到事件数组中,并将位置单元格加载到位置数组中。
在fclose($file);
之后,我做了print_r($time);
并返回了Array ( [0] => Time )
。但在get_data($time, $events, $location);
之后,我做了print_r($time);
并获得Array()
。它为什么空白?如何将所有时间单元格加载到时间数组中,将事件单元格加载到事件数组中,将位置单元格加载到位置数组中?
EventsScheduleFriday.csv
Time,Event,Location,
12:30pm,Hilby The Skinny German Juggle Boy,West State Street,
4:45pm,Hilby The Skinny German Juggle Boy,West State Street,
6pm,Finger Lakes Comedy Festival Competition 1st Round (Age 21+),Lot 10,
8pm,Stand-up Comedy Show,Acting Out NY,
10pm,All-Star Comedy Show,Acting Out NY
PHP代码:
<?php
$time = array();
$events = array();
$location = array();
function get_data($time, $events, $location) {
$file = fopen(__DIR__."/../data/EventsScheduleFriday.csv", "r"); //read .csv file
while(!feof($file)) { //while end of file has not been reached
$content = fgetcsv($file, ","); //converts first line of csv to an array
array_push($time, $content[0]);
array_push($events, $content[1]);
array_push($location, $content[2]);
}
fclose($file); //closes csv file
}
get_data($time, $events, $location);
?>
答案 0 :(得分:2)
如果因为您使用方法范围之外的变量,则会发生这种情况。将这些传递给方法时,会从CSV文件中为它们分配正确的值,但在方法完成时,它们不会在方法外部传递。这就是PHP处理变量和范围的方式。您需要做的是通过引用传递变量。这样做,PHP也会在方法之外传递指定的值。
为此,您需要更改为行:
function get_data($time, $events, $location) {
要:
function get_data(&$time, &$events, &$location) {