将 php 数组转换为 csv 字符串
2022-08-30 19:30:10
我有几种方法可以将php数组转换为来自stackoverflow和google的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; }
谢谢
普里托姆。