PHP多维数组到CSV

时间:2016-10-20 18:15:05

标签: php arrays forms csv post

我有一个包含多维数组和单个数组的表单。当用户单击按钮时,可以动态生成多维数组,以便他们可以像其他作业或其他程度一样添加字段。

对于多维数组,我想测试以确保它们正在收集数据。我在我的教育输入集合print_r($_POST["educationHistory"]上运行以下命令来测试数组并确保它正确记录。它是,它以下列方式输出数组内容:

Array ( [0] => WLU [1] => Math [2] => 2016 )

并且对于之后记录的每个数组,数字都会改变,等等。

当我尝试将多维数组保存到.CSV时,它的结果完全不同。

我正在尝试将print_r布局(Array ( [0] => WLU [1] => Math [2] => 2016 ))的上述样式推送到我输出所有表单字段的csv文件,但我没有运气。

这样的事情可能吗?

我只能打印出这样的数组值(使用上面的例子):WLU Math 2016,但是当有2个或3个条目时,这会让人感到困惑。

有什么建议吗?

以下是完整代码:

PHP

<?php

//page one inputs

$firstName = $_POST["firstName"];
$lastName = $_POST["lastName"];
$homeAddress = $_POST["homeAddress"];
$homeAddressTwo = $_POST["homeAddressTwo"];
$city = $_POST["city"];
$province = $_POST["province"];
$postalCode = $_POST["postalCode"];
$homePhone = $_POST["homePhone"];
$personalEmail = $_POST["personalEmail"];
$confirmEmail = $_POST["confirmEmail"];
$oectaNumber = $_POST["oectaNumber"];
$memberStatus = $_POST["memberStatus"];
$teacherTraining = $_POST["teacherTraining"];
$teachingYears = $_POST["teachingYears"];


$employmentHistory = $_POST["employmentHistory"];
$employmentHistoryValues = "";

foreach($employmentHistory as $value)
{
    $employmentHistoryValues .= $value . " ||| ";
}

$nonSchoolEmployer = $_POST["nonSchoolEmployer"];
$nonSchoolEmployerValues = "";
foreach($nonSchoolEmployer as $employerValue)
{
    $nonSchoolEmployerValues .= $employerValue . " ||| ";
}


$educationHistoryValues = "";
foreach(print_r($_POST["educationHistory"]) as $educationValue)
{
    $educationHistoryValues .= $educationValue;
}



$csvdata = $firstName . ", " . $lastName . ", " . $homeAddress . ", " . $homeAddressTwo . ", " . $city . ", " . $province . ", " . $postalCode . ", " . $homePhone . ", " . $personalEmail . ", " . $confirmEmail . ", " . $oectaNumber . ", " . $memberStatus . ", " . $teacherTraining . ", " . $teachingYears . "," . $employmentHistoryValues . "," . $nonSchoolEmployerValues . "," . $educationHistoryValues;

$fp = fopen("formdata.csv", "a");

if($fp)
{
    fwrite($fp, $csvdata . "\n");
    fclose($fp);
}

?>

HTML:

<div id="educationHistory" name="educationHistory[]">
    <input type="text" class="three-lines" name="educationHistory[]" id="educationInstitution_1" placeholder="Institution" onblur="this.placeholder='Institution'" onfocus="this.placeholder=''" onkeyup="checkPage2()" />

    <input type="text" class="three-lines" name="educationHistory[]" id="degreeFromInstitution_1" placeholder="Degree/Diploma" onblur="this.placeholder='Degree/Diploma'" onfocus="this.placeholder=''" onkeyup="checkPage2()" />

    <input type="date" class="three-lines" name="educationHistory[]" id="educationalDates_1" />
    <input type="button" value="+" onclick="addEducation()" />
</div><!--end educationHistory Div -->                
</div><!--end of education div-->

1 个答案:

答案 0 :(得分:0)

假设这个$ _POST数据:

$_POST['employmentHistory']=array('somehere','somethere');
$_POST['nonSchoolEmployer']=array('somebody','somebodyelse');
$_POST['educationHistory']=array('heapshere','heapsoverthere','andtheretoo');
$_POST['firstName']="John";
$_POST['lastName']="Smith";
$_POST['homeAddress']="1 Here St.";
$_POST['homeAddressTwo']="Apt 2";
$_POST['city']="Townsville";
$_POST['province']="Quebec";
$_POST['postalCode']="H1C";
$_POST['homePhone']="418-555-0157";
$_POST['personalEmail']="418-555-0135";
$_POST['confirmEmail']="js@H1C.ca";
$_POST['oectaNumber']="999999";
$_POST['memberStatus']="Active";
$_POST['teacherTraining']="some";
$_POST['teachingYears']="eleventeen";

以下是您的代码:(我有义务提醒您,您的$ _POST数据应首先进行验证/清理。)

$employmentHistoryValues=implode(' ||| ',$_POST["employmentHistory"]);
// this avoids the trailing ' ||| ' that your method produced.

$nonSchoolEmployerValues=implode(' ||| ',$_POST["nonSchoolEmployer"]);
// this avoids the trailing ' ||| ' that your method produced.

// Your foreach(print_r()) will throw a WARNING and should not be used.
// Your method smashes all $_POST["educationHistory"] data together with no separator, so I will too.
$educationHistoryValues=implode('',$_POST["educationHistory"]);

// declare the keys of the $_POST values you want to extract
$postkeys=array('firstName','lastName','homeAddress','homeAddressTwo','city','province','postalCode','homePhone','personalEmail','confirmEmail','oectaNumber','memberStatus','teacherTraining','teachingYears');

// join the single-value elements with the multi-value elements and glue them together as a comma-space-separated string.
$csvdata=implode(', ',array_merge(array_intersect_key($_POST,array_flip($postkeys)),[$employmentHistoryValues,$nonSchoolEmployerValues,$educationHistoryValues]));

echo "csvdata = $csvdata";  // remove after you verify result as correct

if($fp=fopen("formdata.csv", "a")){
    fwrite($fp,$csvdata."\n");
    fclose($fp);
}

输出:

csvdata = John, Smith, 1 Here St., Apt 2, Townsville, Quebec, H1C, 418-555-0157, 418-555-0135, js@H1C.ca, 999999, Active, some, eleventeen, somehere ||| somethere, somebody ||| somebodyelse, heapshereheapsoverthereandtheretoo

编辑:我刚刚重新阅读了您的问题,并没有解决表单字段命名问题 ...

如果您尝试以三分之一方式批量处理educationHistory数据,那么您可以设置如下表单:

<input type="text" class="three-lines" name="educationHistory[0][institution]" id="educationInstitution_1" placeholder="Institution" onblur="this.placeholder='Institution'" onfocus="this.placeholder=''" onkeyup="checkPage2()" />

<input type="text" class="three-lines" name="educationHistory[0][degree]" id="degreeFromInstitution_1" placeholder="Degree/Diploma" onblur="this.placeholder='Degree/Diploma'" onfocus="this.placeholder=''" onkeyup="checkPage2()" />

<input type="date" class="three-lines" name="educationHistory[0][date]" id="educationalDates_1" />
<input type="button" value="+" onclick="addEducation()" />

addEducation()增加下一批字段的索引。

接收:

$_POST['educationHistory']=array(
    array('institute'=>'WLU','degree'=>'Math','date'=>'2016'),
    array('institute'=>'UQ','degree'=>'English','date'=>'2012')
);

您的处理代码可以是:

$educationHistoryValues='';
foreach($_POST['educationHistory'] as $a){
    $educationHistoryValues.=($educationHistoryValues!=''?', ':'').implode(' ',$a);
}

echo "educationHistoryValues = $educationHistoryValues";
//    educationHistoryValues = WLU Math 2016, UQ English 2012