2013-08-22 109 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