为CSV文件添加新列

时间:2017-04-04 15:11:57

标签: php multiple-columns export-to-csv

我有不同长度的树阵列,我想在csv文件的列中显示每个数组。这是我正在使用的PHP脚本文件,但没有成功;我得到了重复的数据。 我尝试的尝试是用空字符串提供空单元格,这样我就可以有3列具有相同的长度。

$categories = get_categories( $args ); 
        $categories_level_1 = array();
        $categories_level_2 = array();
        $categories_level_3 = array();

        foreach ($categories as  $cat ) {
            $cat_level =count( get_ancestors($cat->term_id, 'category') );
            if($cat_level == 0){
                $categories_level_1[] = $cat; 

            }else{
                if($cat_level == 1){
                    $categories_level_2[] = $cat; 

                }elseif($cat_level == 2){
                    $categories_level_3[] = $cat; 

                }
            }
        } 
        fputcsv($file, array(utf8_decode('Catégories level 1')));

        $i=0; 
        foreach ($categories_level_1 as $category) {
            $i++; 
            $categorie_name = array(rw_mb_convert_encoding($category->name));
            fputcsv($file, $categorie_name );
            print_flush("\n liine created");

        } 
        while( $i < count($categories_level_2)){
            $i++;
            fputcsv($file,  array(" "));
            print_flush("\n liine  vide created");
        }


        fclose($file);

        $newCsvData = array();

        foreach ($categories_level_2 as $cat) { 
            if (($handle = fopen($csv_file_path, "r")) !== FALSE) {
                while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                    $data[] = rw_mb_convert_encoding($cat->name);
                    $newCsvData[] = $data;
                }
                fclose($handle);
            }


        } 
        $handle = fopen($csv_file_path, 'w');

        foreach ($newCsvData as $line) {
           fputcsv($handle, $line);
        } 
        fclose($handle);

我应该使用以下结构获取我的列:    enter image description here

但实际上,这是我得到的结果:  enter image description here

0 个答案:

没有答案