如何从MySQL获取和组合数据,然后在PHP中插入到数组中

时间:2013-07-03 17:25:08

标签: php mysql arrays pdo

这个问题对我的需求非常具体,因此我找不到最佳方法。

我想要做的是从表格name中抓取surnamepeople,然后将它们合并到一个数组中,最终得到这样的结果:

"Bob Jones","Tony Wright", ..等等。

我正在使用PDO。这就是我所拥有的:

$attrs = array(PDO::ATTR_PERSISTENT => true);

// connect to PDO
$pdo = new PDO("mysql:host=localhost;dbname=new", "root", "root", $attrs);

// the following tells PDO we want it to throw Exceptions for every error.
// this is far more useful than the default mode of throwing php errors
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$conn = $pdo->prepare("SELECT name, surname FROM people");

$conn->execute();
$results = $conn->fetchAll();

foreach($results as $row){

    $fullName = $row['name'] . "," . $row['surname'];

    print_r($fullName);
} 

我已经尝试过一些东西,我只是暂时坚持使用这段代码。任何帮助或建议都非常感谢。

4 个答案:

答案 0 :(得分:1)

$arr = array();
foreach($results as $row) {
   $arr[] = "{$row['name']},{$row['surname']}";
}
echo implode($arr);

答案 1 :(得分:1)

您也可以在SQL中解决此问题,因此不再需要foreach。

只需替换

SELECT name, surname FROM people

SELECT CONCAT_WS(' ', name, surname) FROM people

答案 2 :(得分:0)

从数据库中获取行后,需要循环结果集并将组合名称分配给新数组:

<?php

// result set from database
$results = $conn->fetchAll();

// create an empty array to store our names
$names = array();

// loop over result set and add entry to $names array
foreach ($results as $result) {
    $names[] = $row['name'] . ' ' . $row['surname'];
}

print_r($names);

答案 3 :(得分:0)

$fullname =array();
foreach($results as $row){
        $fullName = $row['name'] . " " . $row['surname'];
}
print_r($fullname);
相关问题