2016-11-25 63 views
0

我想將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);  

?> 

回答

2

原因出現這種情況,如果是因爲你使用的方法範圍以外的變量。將這些傳遞給方法時,會從CSV文件中爲它們分配正確的值,但在方法結束時不會在方法外執行。這就是PHP如何處理變量和範圍。你需要做的是通過引用傳遞變量。這樣做,PHP將在方法外攜帶指定的值。

要做到這一點,您需要更改到行:

function get_data($time, $events, $location) { 

要:

function get_data(&$time, &$events, &$location) {