0

这个问题非常适合我的需求,因此我找不到最好的方法。

我想做的是从表中获取name并合并到一个数组中,最终得到这样的结果:surnamepeople

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

我为此使用 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

4 回答 4

1

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

只需更换

SELECT name, surname FROM people

SELECT CONCAT_WS(' ', name, surname) FROM people
于 2013-07-04T07:14:24.570 回答
1
$arr = array();
foreach($results as $row) {
   $arr[] = "{$row['name']},{$row['surname']}";
}
echo implode($arr);
于 2013-07-03T17:27:57.477 回答
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);
于 2013-07-03T17:27:49.517 回答
0
$fullname =array();
foreach($results as $row){
        $fullName = $row['name'] . " " . $row['surname'];
}
print_r($fullname);
于 2013-07-03T17:38:59.133 回答