如何将自定义键值对添加到现有的 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"
}
]
这可能吗?
最佳答案
您可以在 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]);
(这主要是在别处重用此代码时,因为我不知道包含单引号的有效国家/地区名称)
关于php - 修改并添加到 MySQL 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52676240/