2013-08-22 104 views
0

基本上,我通過HTML上傳表單加載CSV文件,然後將其保存到PHP中。 我需要創建一個foreach循環來以某種方式逐行打印文件。如何使用foreach循環將CSV文件保存到變量?

我不確定如何做到這一點,因爲我老實說從未設計過一個PHP foreach循環。

這是捕捉和保存從CSV多維數組文件

$csv_array = array(array()); 
$file = fopen($_FILES['upload_csv']['tmp_name'], 'r'); 
if($file) 
{ 
    while (($line = fgetcsv($file)) !== FALSE) 
    { 
     $csv_array[] = array_combine(range(1, count($line)), array_values($line)); 
    } 

    fclose($file); 
} 

這是我當前的foreach循環這是不是在所有我抓住,並從一個稍微改變運作良好的代碼我其他功能。

$all_questions; 
if(!empty($csv_array)) 
{ 
    foreach($csv_array as $question) 
    { 
     $all_questions = $all_questions . implode(',',$question) . "\n"; 
    } 
} 

所以在最後,我需要我的foreach循環都要經過我的多維數組將其保存爲一個大的字符串。如果我的CSV文件是這樣的:

question1,answer1,answer2,answer3,answer4 
question2,answer1,answer2,answer3,answer4 
question3,answer1,answer2,answer3,answer4 

我需要它以完全相同的格式保存到一個變量。我還需要保留多維數組,因爲我需要其他原因。

回答

0

以某種方式結束了我自己。必須跳過第一個元素,以便解釋array_slice。

foreach (array_slice($csv_array,1) as $row) 
{ 
    $all_questions = $all_questions . $row[1] . ","; 
    $all_questions = $all_questions . $row[2] . ","; 
    $all_questions = $all_questions . $row[3] . ","; 
    $all_questions = $all_questions . $row[4] . ","; 
    $all_questions = $all_questions . $row[5]; 
    $all_questions = $all_questions . "\n"; 
} 
+0

會更容易使用'join()'。 _trigger_應該讀取幾乎相同的許多行。 – alex