[英]How to save a CSV file to a variable with a foreach loop?
基本上,我是通过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
我需要将其保存到完全相同格式的变量中。 我还需要保留多维数组,因为出于其他原因需要它。
最终以某种方式自己完成。 必须跳过第一个元素,以便解释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";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.