繁体   English   中英

PHP Foreach多个数组写入csv文件

[英]PHP Foreach multiple arrays write to csv file

我将以下数据重复五次,并希望返回该数组并将该数组写入我的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文件。

你能帮我吗? 谢谢

您必须遍历数组并将每条记录写入文件:

<?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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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