检查while循环键存在于单独的数组中

时间:2014-08-17 16:50:22

标签: php mysql arrays csv fputcsv

检查了各种问题但却无法找到我需要的东西,我有点不知所措。

我试图通过解析列名并将有效列名添加到$colnames数组,然后将这些值作为标题添加到CSV然后仅显示来从MySQL中选择要导出为CSV的列通过while循环从数据库中获取相关数据。

我特别关注以下问题:How to get all the key in multi-dimensional array in php

以下是代码:

function query_to_csv($query, $filename, $attachment = false, $headers = true, $specs_off = false) {

    if($attachment) {
        // send response headers to the browser
        header( 'Content-Type: text/csv; charset=UTF-8' );
        header( 'Content-Disposition: attachment;filename='.$filename);
        $fp = fopen('php://output', 'w');
    } else {
        $fp = fopen($filename, 'w');
    }

    $result = mysql_query($query) or die( mysql_error() );

    if($headers) {
        // output header row (if at least one row exists)
        $row = mysql_fetch_assoc($result);
        if($row) {

            // PRODUCTS TABLE SPECIFIC - get rid of specs_ and free_ columns so have nicer data set for user
            if($specs_off) { 

                $columnames = array_keys($row);   
                $colnames = array(); 
                //$colnames = array_keys($row);

                foreach($columnames as $key => $value) {

                    if((substr_count($value, "spec_") < 1) && (substr_count($value, "free_") < 1))  {
                        array_push($colnames, $value);                                  
                    }

                }
            }
            else {
                $colnames = array_keys($row);
            }

            // add in additional columns if exporting client data  
            if($table == 'clients') {array_push($colnames, "products", "last_order_date");}

            //write the colnames to the csv file
            fputcsv($fp, $colnames);

            // reset pointer back to beginning
            mysql_data_seek($result, 0);
        }
    } // done with the headers etc, now lets get on with the data


    // clear out and create the $row_data array 
    $row_data = array(); 

    // run through the row array adding values to row_data as we go 
    while($row = mysql_fetch_assoc($result)) {

        // create the array_keys_multi from https://stackoverflow.com/questions/11234852/how-to-get-all-the-key-in-multi-dimensional-array-in-php/11234924#11234924
        function array_keys_multi(array $array) {
            $keys = array();

            foreach ($array as $key => $value) {
                $keys[] = $key;

                if (is_array($array[$key])) {
                    $keys = array_merge($keys, array_keys_multi($array[$key]));
                }
            }

            return $keys;

        }

        // run the function on the $row array
        array_keys_multi($row); 

        // now use the $keys array  
        foreach($keys as $key => $value) {

             // check if the value is in the colnames array and if so push the data on to the $row_data array ready for export to CSV
             if(in_array($value, $colnames)) {
                 array_push($row_data, $row[$value]);
             }
        }

        // now we are ready to write the CSV
        fputcsv($fp, $row_data);

    }

    fclose($fp);
    exit;

} // end of query_to_csv

// Write the sql statement
$sql = "SELECT * FROM ".$table." "; 
if(isset($where_1_col)) { $sql .= " WHERE `".$where_1_col."` = '".$where_1_val."'"; }
if(isset($where_2_col)) { $sql .= " AND `".$where_2_col."` = '".$where_2_val."'"; }
if(isset($where_3_col)) { $sql .= " AND `".$where_3_col."` = '".$where_3_val."'"; }
if(isset($where_4_col)) { $sql .= " AND `".$where_4_col."` = '".$where_4_val."'"; }
if(isset($order_by_col)) { $sql .= " ORDER BY `".$order_by_col."` ". strtoupper($order_by_dir) ." "; }

// output as an attachment
query_to_csv($sql, $table."_export.csv", true, true, true);

所有我得到的是所选列名的大量导出,重复次数与初始查询中的值一样多。我不知道如何获取价值。

欢迎任何有关我出错的建议或如何更妥善地进行此项建议。

1 个答案:

答案 0 :(得分:0)

您似乎只是将新行数据附加到$row_data,但从未清除该数组。

array_push($row_data, $row[$value]);

我做了什么来解决它:

移动

// clear out and create the $row_data array 
$row_data = array(); 

进入 while循环。

更改

// clear out and create the $row_data array 
$row_data = array(); 
while($row = mysql_fetch_assoc($result)) {
...
}

while($row = mysql_fetch_assoc($result)) {
// clear out and create the $row_data array 
$row_data = array(); 
...
}

注意:
您到处使用$table但从未定义它。就像这里if($table == 'clients')
如果它是全局变量,您还需要为函数添加global $table或参数。

修改
正如我在您的问题评论中提到的,您可以使用array_keys()来获取密钥。 php.net/manual/de/function.array-keys.php
然后改变

array_keys_multi($row); 

$keys =  array_keys($row);

之后,您可以删除array_keys_multi()

此外,您可以在while循环前移动该部分,因为您只需要计算一次所需的列名,而不是每次迭代。