将关联数组导出到CSV,包括每个数组的null和标头

时间:2019-01-30 14:04:44

标签: php

我正在尝试将关联数组/对象导出到CSV文件。 下面是我正在使用的代码示例:

function array_keys_multi(array $array) {
    $uniquekeys = array();
    foreach ($array as $splitArray) {
        $keys = array_keys($splitArray);
        $uniquekeys = array_merge($keys, $uniquekeys);
    }
    return array_unique($uniquekeys);
}

function outputCsv($fileName, $Array)
{
    ob_clean();
    header('Pragma: public');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Cache-Control: private', false);
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment;filename=' . $fileName);    
    if(isset($Array)){
        $fp = fopen('php://output', 'w');
        $keys = array_keys_multi($Array);
        fputcsv($fp, $keys);
        $keys = array_flip($keys);
        foreach($Array AS $values){
            fputcsv($fp, array_merge($keys,$values));
        }
        fclose($fp);
    }
    ob_flush();
}

$data = array(
    array('item' => 'Server', 'cost' => 10000, 'approved_by' => 'Joe'),
    array('item' => 'Mt Dew', 'cost' => 1.25, 'approved_by' => 'John'),
    array('item' => 'IntelliJ', 'cost' => 500, 'approved_by' => 'James', 'extra' => 'data1', 'extra1' => 'data2', 'extra3' => ''),
    array('item' => 'IDEA', 'cost' => 500, 'approved_by' => 'James', 'extra1' => 'data2', 'extra3' => 'data3')
);

outputCsv('expenses.csv', $data);

输出

item     cost   approved_by extra1  extra3  extra
Server   10000  Joe         3       4       8
Mt Dew   1.25   John        3       4       8
IntelliJ 500    James      data2            data1
IDEA     500    James      data2    data3   8

所需的输出

item     cost  approved_by extra extra1 extra3
Server   10000 Joe         null  null   null
MtDew    1.25  John        null  null   null
IntelliJ 500   James       data1 data2  null
IDEA     500   James       data2 null   data3

任何人都可以验证此代码,并让我知道错误在哪里或需要更改吗?

1 个答案:

答案 0 :(得分:1)

一种简单的方法

if pygame.mixer.Channel(0).get_busy() == True:
    print("playing a sound")
else:
    print("not playing")

达到您想要的结果。