如何使用foreach循环将CSV文件保存到变量?

时间:2013-08-22 08:32:06

标签: php arrays foreach

基本上,我是通过HTML上传表单加载CSV文件,然后将其保存到PHP中。 我需要创建一个foreach循环,以某种方式逐行打印出文件。

我不确定如何做到这一点因为我以前从未设计过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

我需要将它以完全相同的格式保存到变量中。我需要保留我的多维数组,因为我还需要它。

1 个答案:

答案 0 :(得分: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";
}