dongli8862 2014-10-06 15:22
浏览 97

将逗号分隔的数据从MySql转换为php数组

What would be a direct way to turn comma separated data from a mysql table, into a simple php array, other than doing it like I'm doing now?

I current do this in a very messy way by selecting data, then concatenating it into a string, which I later use.

I'm using PDO here.

Data is simple

locations
-------------------
US,UK,SE,DE
DE,SE,CA
GB,US,DE,SE
AU,NZ,GB

pdo

$d = $db->prepare('select locations a from destinations');

$d->execute();

$d->bindColumn('a',$a);

$count = $d->rowCount();

if($count >= 1) {
    $b = '';
    while($row = $d->fetch()) {
        $b .= $a.',';
    }
} else {
    $b = 'No records to display';
}

echo $b;

The output I'm hoping to achieve is just a simple array like below, which is all the rows joined together.

Desired output

array('US','UK','SE','DE','DE','SE','CA','GB','US','DE','SE','AU','NZ','GB')

Can you help?

  • 写回答

2条回答 默认 最新

  • drpmazn9021 2014-10-06 15:29
    关注

    You're almost there. The easiest thing you can do is use explode(',', $b) for the complete string you have now, and frankly, I'm a bit surprised that you couldn't figure that part out after writing all that code.

    Instead of concating everying in PHP, you can also concat it in the query using the GROUP_CONCAT function. This will introduce a limit, though, since the result of GROUP_CONCAT can be at most 32k, if I remember correctly.

    Below is an alternative approach. Here, each row is fetched and exploded to an array immediately. That array is merged with (appended to, actually) to one big resulting array.

    The advantage is that you are not concatting a big string first, which is relatively inefficient, but in practice, I doubt if you can tell the difference in performance.

    $d = $db->prepare('select locations a from destinations');
    
    $d->execute();
    
    // An array for results.
    $results = array();
    
    $d->bindColumn('a',$a);
    
    $count = $d->rowCount();
    
    if($count >= 1) {
        $b = '';
        while($row = $d->fetch()) {
            // explode each row and append it to the array.
            $results = array_merge($results, explode(',', $a));
        }
    } else {
        $b = 'No records to display';
    }
    
    // Display the complete array.
    print_r($results);
    
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向