使用PHP

时间:2017-08-24 06:35:30

标签: php arrays csv fputcsv

我正在尝试通过在写入CSV之前先将数据存储到数组中来将数据插入CSV文件。但我遇到了将多维数组编写到CSV文件的问题。

以下是我的输入结果:

<input type="text" name="names" placeholder="Enter Name" />
<select name="gender">
    <option value="Male">Male</option>
    <option value="Female">Female</option>
</select>
<input type="text" name="age" placeholder="Enter Age" />
<input type="text" name="state" placeholder="Enter State" />

<label>How Did You Find Us?</label>

<input type="checkbox" name="remarks[]" value="Search Engine (eg. Google)"> Search Engine (eg. Google) &nbsp;&nbsp;&nbsp;
<input type="checkbox" name="remarks[]" value="Facebook"> Facebook &nbsp;&nbsp;&nbsp;
<input type="checkbox" name="remarks[]" value="Newspaper Ads"> Newspaper Ads &nbsp;&nbsp;&nbsp;
<input type="checkbox" name="remarks[]" value="Bus-Stop Ads"> Bus-Stop Ads &nbsp;&nbsp;&nbsp;

以下代码是我如何存储输入数据并以CSV文件写入:

$names = filter_input(INPUT_POST, "names");
$gender = filter_input(INPUT_POST, "gender");
$age = filter_input(INPUT_POST, "age");
$state = filter_input(INPUT_POST, "state");
$remarks = $_POST['remarks'];

$inputArr[] = array(
    $names, $gender, $age, $state, $remarks
);

$fp = fopen($_SERVER["DOCUMENT_ROOT"]."/student.csv", "a+");

fputcsv($fp, $inputArr);
fclose($fp);

$inputArr输出如下,这是一个多维数据:

Array
(
    [0] => Melinda
    [1] => Female
    [2] => 23
    [3] => united state
    [4] => Array
        (
            [0] => Facebook
            [1] => Newspaper Ads
            [2] => Bus-Stop Ads
        )

)

我想让数组像下面的数组一样,以便可以将数据插入到CSV中,但我不知道如何使用数据来获取输出,如下所示:

Array
(
    [0] => Melinda
    [1] => Female
    [2] => 23
    [3] => united state
    [4] => Array
    [5] => Facebook
    [6] => Newspaper Ads
    [7] => Bus-Stop Ads
)

2 个答案:

答案 0 :(得分:1)

使用array_merge,在分配给[]时,我认为您不需要inputArr

$inputArr = array_merge(array($names, $gender, $age, $state), $remarks);
$fp = fopen($_SERVER["DOCUMENT_ROOT"]."/student.csv", "a+");

fputcsv($fp, $inputArr);
fclose($fp);

答案 1 :(得分:0)

只需在推送它们之前合并这些值:

代码:(Demo

$names="joe";
$gender="smith";
$age="18";
$state="WA";
$remarks=array('Facebook','Newspaper Ads','Bus-Stop Ads');

$inputArr=array_merge(array($names, $gender, $age, $state),$remarks);
var_export($inputArr);

输出:

array (
  0 => 'joe',
  1 => 'smith',
  2 => '18',
  3 => 'WA',
  4 => 'Facebook',
  5 => 'Newspaper Ads',
  6 => 'Bus-Stop Ads',
)