php
  • postgresql
  • 2014-04-29 160 views -2 likes 
    -2

    我有我的PHP腳本的麻煩從值內修剪空白,因爲我輸出PostgreSQL的查詢結果。的註釋行是從print_r();PHP導出過程中去除空白到csv

    <?php 
    
    $db = pg_connect("host=localhost dbname=test user=test password=test"); 
    $result = pg_query($db, "SELECT * FROM table WHERE field = 'test'"); 
    $array = pg_fetch_all($result); 
    
    //Array ([0] => Array ([id_number] => 214 [country] => Zanzibar [sector] => Unguja [site] => Chumbe Island Coral Park (CHICOP) [username] => n) [1] => Array ([id_number] => 213 [country] => Zanzibar [sector] => Unguja [site] => Chumbe Island Coral Park (CHICOP) [username] => n) 
    
    //************* 
    $array_explode = explode(",", $array); 
    $array_trimmed = array_map("trim", $array_explode); 
    $array_implode = implode(",", $array_trimmed); 
    unset($array_explode); 
    //************* 
    
    $fp = fopen('file.csv', 'w'); 
    
    foreach ($array_implode as $fields) { 
    
    fputcsv($fp, $fields); 
    } 
    fclose($fp); 
    
    
    ?> 
    

    返回的數組如果刪除了分則CSV輸出(只是一大堆不必要的空白的,我已經都具有和不具有implode()嘗試之間的行。此。一直在推動我逼瘋了和任何幫助將不勝感激

    +0

    你不應該在數組上使用'explode'。 'explode'用於將字符串分割成令牌 – Phil

    +0

    @Phil的陣列,我使用爆炸以獲得在所述陣列中的各個值。 – user2727439

    +0

    然後你做錯了。恰當地命名'$ array'已經是數組了 – Phil

    回答

    0

    我能得到它使用您的代碼工作:

    <?php 
    $array = Array (0 => Array ('id_number' => 214, 'country' => 'Zanzibar', 'sector' => 'Unguja', 'site' => 'Chumbe Island Coral Park (CHICOP)', 'username' => 'n'), 
         1 => Array ('id_number' => 213, 'country' => 'Zanzibar', 'sector' => 'Unguja', 'site' => 'Chumbe Island Coral Park (CHICOP)', 'username' => 'n')); 
    
    $fp = fopen('file.csv', 'w'); 
    foreach ($array as $fields) { 
         $array_trimmed = array_map("trim", $fields); 
         fputcsv($fp, $array_trimmed); 
    } 
    fclose($fp); 
    

    從FILE.CSV輸出:

    214,Zanzibar,Unguja,"Chumbe Island Coral Park (CHICOP)",n 
    213,Zanzibar,Unguja,"Chumbe Island Coral Park (CHICOP)",n 
    
    +0

    @rmctrazier感謝您的答覆。我也許應該拿出評論陣列,因爲我只是用它來測試(我現在會拿出來保存任何進一步的混淆)。代碼中的'$ array'值傳遞了一個值數組,我也將其編輯到原始代碼塊中。再次 – user2727439

    +0

    @rmctrazier感謝您的答覆,問題雖然,沒有什麼在那裏修剪空白?我做appologise,因爲我認爲我輸出關於沒有空格的唯一值! – user2727439

    +0

    我更新了我的答案,包括一個空白被寫入到文件之前修剪領域。 – rmcfrazier

    相關問題