我的数据库中有一个名单列表。
我正在尝试将结果从PDO :: fetchAll()函数转换为获得类似字符串的结果:
“name1”,“name2”,“name3”等。
我不知道你是否知道我的意思。
谢谢大家的帮助!
答案 0 :(得分:5)
非常fetchAll()
手册页包含的代码可以让您获得易于内爆的1维数组
$result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
你也可以使用Mysql的group_concat()
函数来获取SQL中的字符串。
但了解数据的目的地至关重要。
答案 1 :(得分:-1)
/**
* Formats a line (passed as a fields array) as CSV and returns the CSV as a string.
* Adapted from http://us3.php.net/manual/en/function.fputcsv.php#87120
*/
function arrayToCsv( array &$fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
$delimiter_esc = preg_quote($delimiter, '/');
$enclosure_esc = preg_quote($enclosure, '/');
$output = array();
foreach ( $fields 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 ) ) {
$output[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
}
else {
$output[] = $field;
}
}
return implode( $delimiter, $output );
}