简体   繁体   中英

PHP Multi-Dimensional Array to CSV

I have a form with multidimensional arrays and single arrays. The multidimensional arrays can by dynamically generated when a user clicks a button so they can add a field like another job, or another degree.

In the case of the multidimensional arrays, I wanted to test to make sure they were collecting data. I ran the following on my Education Input Collection print_r($_POST["educationHistory"] to test the array and make sure it's logging correctly. It is and it outputs the array content in the following manner:

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

and for each array logged after, the numbers change and so on.

When I try and save the multidimensional array to the .CSV it comes out quite differently.

I'm trying to push the above style of the print_r layout (Array ( [0] => WLU [1] => Math [2] => 2016 )) to the csv file I am outputting all the form fields to, but I am having no luck.

Is such a thing possible?

I've only gotten as far as being able to print the array values like this(using the above example): WLU Math 2016 but that can get confusing when there are 2 or 3 entries.

Any advice?

Here is the full code:

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-->

Assuming this $_POST data:

$_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";

Here is your code: (I am obligated to warn you that your $_POST data should first be validated/sanitized.)

$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);
}

Output:

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

Edit: I just re-read your question and didn't address the form field naming issue ...

If you are trying to batch the educationHistory data in threes, then you can set up your form like this:

<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()" />

And have addEducation() increment the indices on the next batch of fields.

Receiving:

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

Your processing code could then be:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM