php 将php数组转换为csv字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16352591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert php array to csv string
提问by Pritom
I have several method to transform php array to csv string both from stackoverflow and google. But I am in trouble that if I want to store mobile number such as 01727499452, it saves as without first 0 value. I am currently using this piece of code: Convert array into csv
我有几种方法可以将 php 数组从 stackoverflow 和 google 转换为 csv 字符串。但是我遇到了麻烦,如果我想存储诸如 01727499452 之类的手机号码,它会保存为没有第一个 0 值。我目前正在使用这段代码: Convert array into csv
Can anyone please help me.
谁能帮帮我吗。
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
)
)
)
My code block:
我的代码块:
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; }
Thanks,
谢谢,
Pritom.
普里托姆。
回答by alexcristea
You could use str_putcsv
function:
你可以使用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);
}
More about this on GitHub, a function created by @johanmeiring.
更多关于GitHub 的信息,这是一个由 @johanmeiring 创建的函数。
回答by Daniel Mensing
This is what you need
这就是你需要的
$out = "";
foreach($array as $arr) {
$out .= implode(",", $arr) . PHP_EOL;
}
It runs through your array creating a new line on each loop seperating the array values with a ",".
它贯穿您的数组,在每个循环上创建一个新行,用“,”分隔数组值。
回答by James Holderness
Are you sure the numbers are actually being saved without the leading zero? Have you looked at the actual CSV output in a text editor?
您确定这些数字实际上是在没有前导零的情况下保存的吗?您是否在文本编辑器中查看过实际的 CSV 输出?
If you've just opened up the CSV file in a spreadsheet application, it is most likely the spreadsheet that is interpreting your telephone numbers as numeric values and dropping the zeros when displaying them. You can usually fix that in the spreadsheet by changing the formatting options on that particular column.
如果您刚刚在电子表格应用程序中打开 CSV 文件,很可能是电子表格将您的电话号码解释为数值并在显示它们时去掉零。您通常可以通过更改特定列上的格式选项来修复电子表格中的问题。
回答by wgp
Since it's a CSV and not something like JSON, everything is going to be read as a string anyway so just convert your number to a string with:
由于它是 CSV 而不是 JSON 之类的,因此无论如何都将作为字符串读取所有内容,因此只需将您的数字转换为字符串:
(string)$variable
strval($variable)
(which I would prefer here)- concatenate with an empty string like
$variable . ''
(string)$variable
strval($variable)
(我更喜欢这里)- 连接一个空字符串,如
$variable . ''
PHP's gettype()
would also be an option. You can type cast every field to a string (even if it already is one) by using one of the methods I described or you can call out just the number field you're after by doing this:
PHP 的gettype()
也将是一个选项。您可以使用我描述的方法之一将每个字段类型转换为字符串(即使它已经是一个),或者您可以通过执行以下操作来调用您所追求的数字字段:
if (gettype($field) == 'integer' || gettype($field) == 'double') {
$field = strval($field); // Change $field to string if it's a numeric type
}
Here's the full code with it added
这是添加的完整代码
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;
}
回答by Julien
I'm using this function to convert php array to csv. It's working also for multidimensional array.
我正在使用此函数将 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);
}
回答by Norbert
The function above is not exactly right cause it considers \n like an element, which is not what we want as each line must be only separated by \n. So a more efficient code would be:
上面的函数并不完全正确,因为它认为 \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);
}
回答by Dion Truter
Here is a solution that is a little more general purpose. I was actually looking for a way to make string lists for SQL bulk inserts. The code would look like this:
这是一个更通用的解决方案。我实际上是在寻找一种为 SQL 批量插入制作字符串列表的方法。代码如下所示:
foreach ($rows as $row) {
$string = toDelimitedString($row);
// Now append it to a file, add line break, whatever the need may be
}
And here is the useful function that I ended up adding to my tookit:
这是我最终添加到我的 takeit 中的有用功能:
/**
* 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;
}