【问题标题】:Convert result from PDO::fetchAll() to array like [closed]将 PDO::fetchAll() 的结果转换为数组,如 [关闭]
【发布时间】:2013-05-15 03:36:15
【问题描述】:

我有一个来自我的数据库的名字列表。

我正在尝试将 PDO::fetchAll() 函数的结果转换为类似字符串的结果:

"name1","name2","name3" 等

我不知道你是否明白我的意思。

感谢大家的帮助!

【问题讨论】:

  • 请提供您查询的示例输出,无论如何您将使用一个好的 ol' implode 函数结束。
  • 请编辑您的问题以包含代码的相关部分,以便有人可以帮助您。
  • 这个"name1","name2","name3" 字符串的目的地是什么?

标签: php database arrays string pdo


【解决方案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 );
}

【讨论】:

  • 您当然只是 猜测 OP 对 CSV 输出感兴趣...
  • 他就是这么说的,deceze
  • Ctrl+F, "CSV"...您的答案是此页面上唯一提到 CSV 的内容...?!
  • 引用 OP(因为显然有人没有读过):“我正在尝试将 PDO::fetchAll() 函数的结果转换为类似字符串的结果:“name1”, “名称 2”、“名称 3”等”在我看来,这就像一个 CSV。
  • 看起来像 CSV,但也许 OP 只想要一个一维 array...
【解决方案2】:

fetchAll() 手册页包含可让您获得可轻松内爆的一维数组的代码

$result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);

您也可以使用 Mysql 的 group_concat() 函数从 SQL 中获取字符串。

但了解数据的目的地至关重要。

【讨论】:

  • 完美,非常感谢!
  • 请注意 - FETCH_COLUMN 实际上只获取 1 列 - “即使 SQL 语句本身可能每行返回多个列”
猜你喜欢
  • 2020-04-06
  • 1970-01-01
  • 2018-06-26
  • 2015-12-13
  • 1970-01-01
  • 2020-12-23
  • 1970-01-01
  • 1970-01-01
  • 2013-08-20
相关资源
最近更新 更多