我正在通过来自邀请行的sender_id获取邀请数和每个邀请的行,我正在从用户表中检索用户的详细信息。
我想在同一个邀请数组中添加用户的详细信息。我试着像这样添加。
function getInvitations()
{
$database = new Database(ContactsConstants::DBHOST,ContactsConstants::DBUSER,ContactsConstants::DBPASS,ContactsConstants::DBNAME);
$dbConnection = $database->getDB();
$stmt = $dbConnection->prepare("SELECT * FROM `Invitation` WHERE Invitation.invitee_no = ?");
$stmt->execute(array($this-> invitee_no));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$invitations = array();
if (count($rows) > 0) {
foreach($rows as $row)
{
$stmt = $dbConnection->prepare("Select * from Users where user_id =?");
$stmt->execute(array($row['sender_id']));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$invitations[] = $row;
$invitations[] = $result;
}
$response = array("status" => 1, "message" => "Success", "Invitations" => $invitations);
return json_encode($response);
}
else {
$response = array("status"=>-1,"message"=>"Invitations list is empty");
return json_encode($response);
}
}
输出我是这样的:
{
"status": 1,
"message": "Success",
"Invitations": [
{
"invitation_id": "369",
"date": "12/08/2016",
"invitee_no": "8655864341",
"status": "1",
"sender_id": "44"
},
{
"user_id": "44",
"user_name": "Angel",
"password": "angel",
"profile_image": "a8625093a2e95ee6b5042456b7cccc20.png",
"device_id": "eVOnz8AMVOs:APA91bHuq9Q4FLcOewUCSAQu79aZNeQsb4710k66g1MHDfZUZWa4ZcARs0SekUfnYUt5sTiKeXfFk_Gg_LdtSKk-pTAaQLxPe9UMkYG9-d-IkDRlGYxkzonQ1h2YN78S7RU0x90NAby_",
"mobile_no": "9090966666",
"email_id": "kjfhg@half.com",
"full_name": "ajjdjd",
"job_title": "sxsaca",
"home_address": "scacac",
"work_phone": "ugiuygitf",
"work_address": "bbuyiytfi"
},
]}
但我希望在一个数组中同时包含两个细节。我怎么能得到这个? 有人能帮忙吗?谢谢..
答案 0 :(得分:1)
问题是你正在推动$invitations
变量两个不同的关联数组。
这里的解决方案是将两个数组(array_merge)的元素合并为一个,然后将其推送到$invitation
。
尝试更改此代码:
$invitations[] = $row;
$invitations[] = $result;
由此:
$invitations[] = array_merge($row, $result);
编辑:
要解决警告array_merge(): Argument #2 is not an array
,请尝试使用转换强制$result
数组类型:
$invitations[] = array_merge($row, (array)$result);
答案 1 :(得分:1)
使用以下功能,因为@nanocv告诉你必须改变如下
<?php
function getInvitations()
{
$database = new Database(ContactsConstants::DBHOST,ContactsConstants::DBUSER,ContactsConstants::DBPASS,ContactsConstants::DBNAME);
$dbConnection = $database->getDB();
$stmt = $dbConnection->prepare("SELECT * FROM `Invitation` WHERE Invitation.invitee_no = ?");
$stmt->execute(array($this-> invitee_no));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$invitations = array();
if (count($rows) > 0) {
foreach($rows as $row)
{
$stmt = $dbConnection->prepare("Select * from Users where user_id =?");
$stmt->execute(array($row['sender_id']));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$final_array = array_merge($row,$result);
$invitations[] = $final_array;
}
$response = array("status" => 1, "message" => "Success", "Invitations" => $invitations);
return json_encode($response);
}
else {
$response = array("status"=>-1,"message"=>"Invitations list is empty");
return json_encode($response);
}
}
?>
希望这会有所帮助!