2013-06-28 42 views
0

我有以下數據重複5次想要回陣列和陣列寫信給我的csv文件:PHP的foreach多個陣列寫入csv文件

<strong>Inventory number:</strong> 
    <input name="inv[]" type="text" size="10" id="inv[]"/> 
    <strong>Description:</strong> 
    <input name="des[]" type="text" size="30"id="des[]"/> 

    <strong>Inventory number:</strong> 
    <input name="inv[]" type="text" size="10" id="inv[]"/> 
    <strong>Description:</strong> 
    <input name="des[]" type="text" size="30"id="des[]"/> 

我做了一個foreach:

for ($i = 0, $rowcount = count($_POST['inv']); $i < $rowcount; $i++) 
    { 
$inv = $_POST['inv'][$i]; // get inventory 
$des = $_POST['des'][$i]; // get description 
     } 

然後有一個寫命令:

if(empty($errorMessage)) 
{ 
    $fs = fopen("data.csv","a") or die("Unable to open file for output"); 
    fwrite($fs,$sn . ", " . $givenname . ", " . $mail . ", " . $uid . ", " . $inv . ", " . $des . ", " . date("Y.m.d H:i:s") . "\n"); 
    fclose($fs); 

    $destination_url = "receipt.php"; 

    header("Location: $destination_url"); 
    exit; 
} 

,但只寫最後一個數組的CSV文件。

你能幫忙嗎? 感謝

+1

你只有一個'fwrite'命令。隨着循環的進行,您的'$ inv'和'$ des'變量會一遍又一遍地被覆蓋。你期望什麼? –

回答

1

您必須通過遍歷數組,每個記錄寫入文件:

<?php 
if(empty($errorMessage)) 
{ 
    $rowcount = count($_POST['inv']); 
    $fs = fopen("data.csv","a") or die("Unable to open file for output"); 
    for ($i = 0; $i < $rowcount; $i++) 
    { 
     $inv = $_POST['inv'][$i]; // get inventory 
     $des = $_POST['des'][$i]; // get description 
     fwrite($fs, $sn . ", " . $givenname . ", " . $mail . ", " . $uid . ", " . 
      $inv . ", " . $des . ", " . date("Y.m.d H:i:s") . "\n"); 
    } 

    fclose($fs); 
} 

$destination_url = "receipt.php"; 
header("Location: $destination_url"); 
+0

非常感謝你 –

+0

@php_beginner請接受答案,如果沒關係 – user4035

+0

我試着告訴我我可以在6分鐘內完成 - 現在完成了,再次感謝你節省了大量的時間 –