将PHP数组CSV字符串(Convert php array to csv string)

2019-09-01 20:07发布

我有几个方法的PHP阵列既从计算器和谷歌变换为csv字符串。 但我有麻烦,如果我想存储的手机号码,如01727499452,其保存为没有第一个0值。 我目前正在使用这段代码: 转换阵列为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; }

谢谢,

然而。

Answer 1:

你可以使用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创建。



Answer 2:

这是你需要什么?

$out = "";
foreach($array as $arr) {
    $out .= implode(",", $arr) . "\r\n";

}

它运行低谷您的阵列创建的每个回路用“”分离该数组值的新线。



Answer 3:

你确定的数字实际上是被保存没有前导零? 你看在文本编辑器的实际CSV输出?

如果您刚刚打开了一个电子表格应用程序的CSV文件,它是最有可能被解释您的电话号码为数字值并显示它们时下探零点电子表格。 你通常可以通过改变对特定列的格式选项修复在电子表格中。



Answer 4:

因为它是一个CSV,而不是像JSON,一切都将是无论如何解读为一个字符串,所以只是你的数字转换为一个字符串:

  • (string)$variable
  • strval($variable) (我宁愿在这里)
  • 与像一个空字符串拼接$variable . '' $variable . ''

PHP的gettype()也将是一种选择。 您可以键入通过使用我描述或可以叫出只是数场你后这样做的方法之一每个字段转换为字符串(即使它已经是一个):

if (gettype($field) == 'integer' || gettype($field) == 'double') {
    $field = strval($field); // Change $field to string if it's a numeric type
}

下面是完整的代码与它添加

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 ) {
            // ADDITIONS BEGIN HERE
            if (gettype($field) == 'integer' || gettype($field) == 'double') {
                $field = strval($field); // Change $field to string if it's a numeric type
            }
            // ADDITIONS END HERE
            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; 
}


Answer 5:

我使用这个功能,PHP数组转换为csv。 它的工作也为多维数组。

public function array_2_csv($array) {
$csv = array();
foreach ($array as $item=>$val) {
if (is_array($val)) { 
    $csv[] = $this->array_2_csv($val);
    $csv[] = "\n";
} else {
    $csv[] = $val;
  }
 }
return implode(';', $csv);
}


Answer 6:

上面的功能是不完全正确的因为它认为\ n喜欢的元素,这是不是我们想要的,因为每个行必须以\ n只能分开。 因此,一个更高效的代码如下:

function array2csv($array, $delimiter = "\n") {
    $csv = array();
    foreach ($array as $item=>$val) 
    {
        if (is_array($val)) 
        { 
            $csv[] = $this->array2csv($val, ";");
        } 
        else 
        {
            $csv[] = $val;
        }
    }
    return implode($delimiter, $csv);
}


Answer 7:

这里是一个解决方案,它是一个小更通用。 我其实是在寻找一种方法,使对SQL批量插入字符串列表。 代码如下所示:

foreach ($rows as $row) {
    $string = toDelimitedString($row);
    // Now append it to a file, add line break, whatever the need may be
}

这里是我最终加入到我的无线工具包的有用的功能:

/**
 * Convert an array of strings to a delimited string. This function supports CSV as well as SQL output since
 * the quote character is customisable and the escaping behaviour is the same for CSV and SQL.
 *
 * Tests:
 *  echo toDelimitedString([], ',', '\'', true) . "\n";
 *  echo toDelimitedString(['A'], ',', '\'', true) . "\n";
 *  echo toDelimitedString(['A', 'B'], ',', '\'', true) . "\n";
 *  echo toDelimitedString(['A', 'B\'C'], ',', '\'', true) . "\n";
 *  echo toDelimitedString([], ',', '\'', true) . "\n";
 *  echo toDelimitedString(['A'], ',', '"', true) . "\n";
 *  echo toDelimitedString(['A', 'B'], ',', '"', true) . "\n";
 *  echo toDelimitedString(['A', 'B"C'], ',', '"', true) . "\n";
 *
 * Outputs:
 *  <Empty String>
 *  'A'
 *  'A','B'
 *  'A','B''C'
 *  <Empty String>
 *  "A"
 *  "A","B"
 *  "A","B""C"
 *
 * @param array $array A one-dimensional array of string literals
 * @param string $delimiter The character to separate string parts
 * @param string $quoteChar The optional quote character to surround strings with
 * @param bool $escape Flag to indicate whether instances of the quote character should be escaped
 * @return string
 */
function toDelimitedString(array $array, string $delimiter = ',', string $quoteChar = '"', bool $escape = true)
{
    // Escape the quote character, since it is somewhat expensive it can be suppressed
    if ($escape && !empty($quoteChar)) {
        $array = str_replace($quoteChar, $quoteChar . $quoteChar, $array);
    }

    // Put quotes and commas between all the values
    $values = implode($array, $quoteChar . $delimiter . $quoteChar);

    // Put first and last quote around the list, but only if it is not empty
    if (strlen($values) > 0) {
        $values = $quoteChar . $values . $quoteChar;
    }

    return $values;
}


文章来源: Convert php array to csv string