2013-04-08 236 views
0

我有以下代碼:如何在一個數組中連接兩個字段?

$result = mysql_query("SELECT first_name, last_name, employeeID FROM ecc_employee WHERE first_name != '' "); 

$resources = array(); 

while ($row=mysql_fetch_array($result)){    
    $name = ($row['first_name']); 
    $id = $row['employeeID']; 

    $resources[] = array(
    'name' => "$name", 
    'id' => "$id" 
    ); 

我需要$名稱同時擁有姓氏和名字。我將如何做到這一點?

我將如何宣佈$名稱=

+1

SELECT CONCAT(first_name的, 「」,姓氏)名稱,僱員FROM ecc_employee WHERE ... – 2013-04-08 14:41:44

+0

$名稱[FIRST_NAME ] =姓氏; – 2013-04-08 14:43:38

回答

2

可以使用CONCAT功能:

SELECT ... 
     CONCAT(first_name, " ", last_name) AS name 
     ... 

在您的代碼:

$result = mysql_query("SELECT CONCAT(first_name, " ", last_name) AS name, employeeID FROM ecc_employee WHERE first_name != '' "); 

裏調用:

$row['name'] 

您也可以命名employeeID as id跳過重新分配數組鍵在while循環:

$result = mysql_query("SELECT CONCAT(first_name, " ", last_name) AS name, employeeID AS id FROM ecc_employee WHERE first_name != '' "); 
$resources = array(); 

while ($row = mysql_fetch_array($result)){    
    $resources[] = $row; 
} 
0

使用PDO

// of course connect goes first 
$sql = "SELECT SELECT CONCAT(first_name, ' ', last_name) name, employeeID id 
     FROM ecc_employee WHERE first_name != ''"; 
$stm = $pdo->prepare($sql); 
$stm->execute(); 
$resources = $stm->fetchAll();