【问题标题】:Generate a CSV file using PHP使用 PHP 生成 CSV 文件
【发布时间】:2021-03-05 20:21:45
【问题描述】:

所以,我想使用 PHP 从与客户的数组中生成 CSV 文件。我已经创建了 CSV 标头('Name','Surname,'Email')。

$customers = array(
array('id_client' => '15', 'name' => 'Michael', 'surname' => 'Andrew', 'email' => 'and@gmail.com',  'is_demo' => '1','introduction' => '0'),
array('id_client' => '16', 'name' => 'Oliver', 'surname' => 'Jake', 'email' => 'oliverj@gmail.com',  'is_demo' => '1','introduction' => '0'),
array('id_client' => '8', 'name' => 'Noah', 'surname' => 'James', 'email' => 'njam@gmail.com',  'is_demo' => '0','introduction' => '0'),);


foreach ($customers as $row =>$key) {

我将其设为 foreach,但我不知道如何为这个数组设置一个条件,只有姓名、姓氏、电子邮件以及 is_demo '1' 的含义。

【问题讨论】:

  • 你可以使用fputcsv
  • 您将使用“if”语句作为条件。有关您正在尝试做的事情的更多详细信息会有所帮助。
  • 我想用 fputcsv 传递 csv 文件中的名称、姓氏、电子邮件以及谁拥有 is_demo '1'

标签: php csv


【解决方案1】:

这应该能让你继续前进。

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$customers = array(
array('id_client' => '15', 'name' => 'Michael', 'surname' => 'Andrew', 'email' => 'and@gmail.com',  'is_demo' => '1','introduction' => '0'),
array('id_client' => '16', 'name' => 'Oliver', 'surname' => 'Jake', 'email' => 'oliverj@gmail.com',  'is_demo' => '1','introduction' => '0'),
array('id_client' => '8', 'name' => 'Noah', 'surname' => 'James', 'email' => 'njam@gmail.com',  'is_demo' => '0','introduction' => '0'),);
//
// This dir need to be writable by the web server user.
//
$fp=fopen("/full/file/path/file","w");

// this is for headding line
foreach ($customers[0] as $key => $val) {
  $csvHeadders[] = $key;
}
fputcsv($fp, $csvHeadders);

foreach ($customers as $customer) {
  if($customer['is_demo'] == '1'){
    fputcsv($fp, $customer);
  }
}

【讨论】:

  • fputcsv($file, array('Nume', 'Surname', 'E-mail'));我已经创建了标题,我只想从数组中获取名称、姓氏、电子邮件,如果客户有 is_demo = '1'。如果我是你最后一个 foreach 我得到一个错误尝试访问 int 类型值的数组偏移量
【解决方案2】:
fputcsv($file, array('Name', 'Surname', 'E-mail'));


foreach ($customers as $row => $key) {
if ($key['is_demo'] === '1') {
    fputcsv($file, array($key['name'], $key['surname'], $key['email']));
} else {
    echo 'Error';
}
}

我只是通过上述条件找到了我如何吸引客户。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-29
    • 2016-03-17
    • 1970-01-01
    相关资源
    最近更新 更多