php - 将 php 数组转换为 csv 字符串

标签 php csv multidimensional-array phone-number

我有几种方法可以从 stackoverflow 和 google 将 php 数组转换为 csv 字符串。但我很麻烦,如果我想存储手机号码,如 01727499452,它保存为没有第一个 0 值。 我目前正在使用这段代码: Convert array into csv

谁能帮帮我

Array   

[1] => Array
    (
        [0] => Lalu ' " ; \\ Kumar
        [1] => Mondal
        [2] => 01934298345
        [3] => 
    )

[2] => Array
    (
        [0] => Pritom
        [1] => Kumar Mondal
        [2] => 01727499452
        [3] => Bit Mascot
    )

[3] => Array
    (
        [0] => Pritom
        [1] => Kumar Mondal
        [2] => 01711511149
        [3] => 
    )

[4] => Array
    (
        [0] => Raaz
        [1] => Mukherzee
        [2] => 01911224589
        [3] => Khulna University 06
    )

)

我的代码块:

function arrayToCsv( array $fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
$delimiter_esc = preg_quote($delimiter, '/');
$enclosure_esc = preg_quote($enclosure, '/');

$outputString = "";
foreach($fields as $tempFields) {
    $output = array();
    foreach ( $tempFields as $field ) {
        if ($field === null && $nullToMysqlNull) {
            $output[] = 'NULL';
            continue;
        }

        // Enclose fields containing $delimiter, $enclosure or whitespace
        if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
            $field = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
        }
        $output[] = $field." ";
    }
    $outputString .= implode( $delimiter, $output )."\r\n";
}
return $outputString; }

谢谢,

普里托姆。

最佳答案

您可以使用 str_putcsv 函数:

if(!function_exists('str_putcsv'))
{
    function str_putcsv($input, $delimiter = ',', $enclosure = '"')
    {
        // Open a memory "file" for read/write...
        $fp = fopen('php://temp', 'r+');
        // ... write the $input array to the "file" using fputcsv()...
        fputcsv($fp, $input, $delimiter, $enclosure);
        // ... rewind the "file" so we can read what we just wrote...
        rewind($fp);
        // ... read the entire line into a variable...
        $data = fread($fp, 1048576);
        // ... close the "file"...
        fclose($fp);
        // ... and return the $data to the caller, with the trailing newline from fgets() removed.
        return rtrim($data, "\n");
    }
 }

 $csvString = '';
 foreach ($list as $fields) {
     $csvString .= str_putcsv($fields);
 }

关于 GitHub 的更多信息,这是一个由@johanmeiring 创建的函数。

关于php - 将 php 数组转换为 csv 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16352591/

相关文章:

php - 使用 JS slider 显示来自电子商店 API 的产品的可嵌入小部件

php - 在 PHP 中读取请求负载

python - 如何创建新的 CSV 文件并将其存储在 Google Cloud Storage 中?

php - 如何将输入字段数组插入 mysql

java - 在多维数组中设置字符串

java - 二维数组求和

php - 如何设置用户权限?

php - 在一条 SQL 语句中从 MySQL 中检索数据

php - 如何使用 CSV MIME 类型?

c# - CsvHelper 映射常量值