如何将自定义键值对添加到现有的SQL结果中?
<?php
require_once "dbaccess.php";
$json = array();
$access = new DatabaseAccess();
$sql = $access->Connect();
$stmt = $sql->prepare("select * from people");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $key => $value){
$json[$key] = $value;
};
echo json_encode($json, JSON_UNESCAPED_SLASHES);
?>
当前JSON结果为:
[
{
"id": "1",
"first_name": "James",
"last_name": "Haze"
},
{
"id": "2",
"first_name": "Neo",
"last_name": "Anderson"
}
]
如何在不修改MySQL数据库的情况下添加到当前元素"country": "Australia"
中?我希望结果看起来像这样:
[
{
"id": "1",
"first_name": "James",
"last_name": "Haze",
"Country": "Australia"
},
{
"id": "2",
"first_name": "Neo",
"last_name": "Anderson",
"Country": "Australia"
}
]
有可能吗?
答案 0 :(得分:1)
您只需在SQL中选择所需的其他“列”即可
$stmt = $sql->prepare("select
id
, first_name
, last_name
, 'Australia' as Country
from people");
顺便说一句,您不应在选择查询中使用*
-这会使它们在添加新列名时表现得很奇怪,而在重命名列时隐藏错误。
如果要选择变量值,可以通过将其直接内插到SQL中来实现:
$stmt = $sql->prepare("select
id
, first_name
, last_name
, '$country_name' as Country
from people");
尽管国家名称不是必需的,但使用(命名的)SQL占位符仍然是一个好习惯,因此您确实应该这样做:
$stmt = $sql->prepare("select
id
, first_name
, last_name
, :country as Country
from people");
$stmt->execute([':country' => $country_name]);
(主要是在其他地方重用此代码时,因为我不知道包含单引号的有效国家/地区名称)
答案 1 :(得分:1)
您可以直接在select
中添加所需的值 $stmt = $sql->prepare("select id
, firt_name
, last_name
, 'Australia' AS country
from people");