2016-10-20 179 views
0

我將字段輸入傳遞給.csv表單,但我想知道是否可以將變量名稱與值打印在一起?打印CVS輸入的變量名稱

這裏是我如何打印到將該.cvs:

PHP

<?php 
$csvdata = $firstName . ", " . $lastName . ", " . $homeAddress . ", " . $homeAddressTwo . ", " . $city . ", " . $province . ", " . $postalCode . ", " . $homePhone . ", " . $personalEmail . ", " . $confirmEmail . ", " . $oectaNumber . ", " . $memberStatus . ", " . $teacherTraining . ", " . $teachingYears . "," . $employmentHistoryValues; 
$fp = fopen("formdata.csv", "a"); 
if($fp) 
    { 
    fwrite($fp, $csvdata . "\n"); 
    fclose($fp); 
    } 
?> 

這裏就是我想要它看起來像:

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

下面是我正在處理這些變體:

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

輸入數據:

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

在CSV文件本身,結果是很容易破解,但是我從繪畫形式有一堆的動態輸入,這將產生多維數組和一些輸入是文字區域,所以我想測試這個理論。

+0

您準確預計什麼輸出結果? – krasipenkov

+0

目前它僅在特定單元格中輸入輸入結果。當我print_r整個表單時,它給出了一個相當整潔的佈局,像這樣:[memberStatus] =>好,其中成員狀態是變量名稱,好的是用戶輸入。會有這樣的事情嗎? –

+0

變量來自哪裏?在你的例子中哪些是動態的(你對它們進行了硬編碼,這對我來說意味着你知道動力學?) – nerdlyist

回答

0

例如,您可以創建一個包含列名稱的標題csv行。你可以做到這一點的:

$csv = 'col1, col2.....'.PHP_EOL; 
    foreach ($data as $item) { 
     $csv .= $item['val1'].','.$item['val2'].....PHP_EOL; 
    } 
    // write $csv to file 

,如果你在Excel中打開或打開辦公室的csv文件這將是有益的。

但是,如果你想鍵名+值:

foreach ($data as $key => $item) { 
     $csv .= $key.'=>'.$item['val1'].','; 
    } 

這是例如對於一個dimensionsl陣列。如果你有多維空間,你會有嵌套循環。

+0

這很整齊!在嵌套循環的情況下,我將如何將其與第二個示例進行整合。例如,假設item1是一個普通的單個輸入,但是項目2是可以動態生成的三個輸入的集合。這看起來代碼明智嗎? –

+0

你可以在問題中添加這個嵌套數組的轉儲+你想要的輸出看起來像 – krasipenkov

+0

非常新的PHP,什麼是「轉儲」見上面修改 –