从查询的ID数组中生成多个csv

时间:2016-07-28 13:34:49

标签: php csv

尝试做

我正在尝试编写一个将运行一次的php文件,该文件为其自己的文件夹中的每个客户端生成一个csv文件及其各自的名称。

我的代码目前做什么

我的代码目前通过大约一半的客户公司名称,并在每个文件夹中输出一个名为“records.csv”的文件,然后我开始一遍又一遍地得到以下两个错误:

  • 第32行目录中为foreach提供的参数无效。
  • fputcsv()期望参数2为数组,字符串在第44行的目录中给出。

创建的文件确实已创建,但没有任何内容正确写入。

我的代码前言

我不喜欢在这里使用嵌套的foreach(对我来说似乎不是一个好习惯),但这只是运行一次但仍然必须拉出所有当前客户端所以第一个语句sql语句有必要的。

<?php
//make connection
$connection = new mysqli($server, $username, $password, $database);

//check connection
if ($connection->connect_error){
die("Connection failed: " . $connection->connect_error);
}

//get IDs for clients
$sql = "SELECT ID FROM wp_posts WHERE post_type = 'clients' GROUP BY post_title";
$IDs = array();
$result = mysqli_query($connection, $sql) or die ("initial query wasn't found");
while ($row = mysqli_fetch_assoc($result)){
$IDs[] = $row["ID"];
}
//query using ID to match parent data
foreach ($IDs as $ID) {
$company_query = "SELECT * FROM wp_posts INNER JOIN wp_postmeta ON wp_postmeta.post_id = wp_posts.ID WHERE post_parent = ".$ID."";
$name_result = mysqli_query($connection, $company_query) or die("this query failed");
$companies = array();
$companies = mysqli_fetch_assoc($name_result);

 foreach ($companies as $company) {
    $folder_raw = $companies["post_title"];
    $folder_clean = preg_replace('/[^A-Za-z0-9\-]/', '', $folder_raw);
    //make directory
    $folder_name = './' . $folder_clean . '/';
    if(!mkdir($folder_name, 0777, true)){
        die("failed to make folder");
    }

    //make and open file
    $file_name = $folder_name . 'records' . ".csv";
    $fp = fopen($file_name, 'w');
    fputcsv($fp, $company);
    //close file
    fclose($fp);
    break;
  }
 }
}
?>

建议更改

foreach ($IDs as $ID) {
$company_query = "SELECT * FROM wp_posts INNER JOIN wp_postmeta ON wp_postmeta.post_id = wp_posts.ID WHERE post_parent = ".$ID."";
$name_result = mysqli_query($connection, $company_query) or die("this query failed");
$companies = array();
$companies = mysqli_fetch_assoc($name_result);
while ($row = mysqli_fetch_assoc($name_result))
 {

    $folder_raw = $row["post_title"];
    $folder_clean = preg_replace('/[^A-Za-z0-9\-]/', '', $folder_raw);
    $folder_name = './' . $folder_clean . '/';
    if(!mkdir($folder_name, 0777, true)){
        die("failed to make folder");
    }
    $file_name = $folder_name . 'records' . ".csv";
    $fp = fopen($file_name, 'w');
    fputcsv($fp, $company);
    fclose($fp);
    break;
}

1 个答案:

答案 0 :(得分:1)

我认为您的问题源于使用mysqli_fetch_assoc。这将获取1行作为关联数组,看起来您将结果视为foreach中的数组数组。这可能有效,因为您自己不使用$company,而是在循环中访问$companies的成员。

我会改变

$companies = array();
$companies = mysqli_fetch_assoc($name_result);

foreach ($companies as $company) {
  $folder_raw = $companies["post_title"];

while ($row = mysqli_fetch_assoc($name_result))
{
  $folder_raw = $row["post_title"];

看看是否有帮助。