php - 将 PHP 数组转换为 JSON 数组并使用 SLIM3 获取响应
问题描述
我在将数据库查询的结果转换为 json 数组时遇到问题。我的输出如下所示:
{
"user_id": "1",
"username": "testuser1",
"user_permissions": [
{
"list_id": "1"
},
{
"list_id": "2"
},
{
"list_id": "3"
}
],
"android_app_id": null,
"iat": 1537694955,
"exp": 1537702155
}
JSON 数组周围的方括号 ({}) 会导致解析客户端响应中的数组时出现问题。我只需要一个像 (1, 2, 3) 这样的简单数组。
数组由数据库查询结果(PHP)生成,然后使用 SLIM3 操作$this->response->withJson
:
$query = "SELECT list_id FROM permissions WHERE user_id='$user_id'";
$sth = $this->dbconnection->prepare($query);
$sth->execute();
$result_permissions = $sth->fetchAll();
return $result_permissions;
我真的很难将数据库结果转换为普通的 JSON 数组,因为 PHP 只知道关联数组(数字或带键),这会导致格式错误的 json 数组。
json 输出返回到服务器。使用 SLIM3 框架,我访问 JSON 数据和权限数组,如下所示:
$user_permissions = $decoded_response['user_permissions'];
现在我尝试获取 list-ids,它使用命令$user_permissions[list'id][0]
给出 1 。print_r
我接下来要做的是使用带有 IN 运算符的数据库查询来检查 permission_ids。因此我需要生成一个像 (1, 2, 3) 这样的数组。我现在被卡住了,因为我不知道如何从 JSON 生成这样的数组。
对我来说,最简单的方法是在数据库查询之后直接生成这样一个数组,并在开始时将其添加到 JSON 中,但我不知道如何实现。
有什么提示吗?
解决方案
如果我了解您需要实现的目标,您可以使用array_column
php 函数获取 list_ids 数组
http://php.net/manual/en/function.array-column.php
$json = '{
"user_id": "1",
"username": "testuser1",
"user_permissions": [
{
"list_id": "1"
},
{
"list_id": "2"
},
{
"list_id": "3"
}
],
"android_app_id": null,
"iat": 1537694955,
"exp": 1537702155
}
';
$arrayFromJson = json_decode($json, true);
$ids = array_column($arrayFromJson['user_permissions'], 'list_id');
print_r($ids);
的输出print_r
将是
Array
(
[0] => 1
[1] => 2
[2] => 3
)
要获得像(1,2,3)
您这样的字符串,可以使用 phpimplode
函数
https://secure.php.net/manual/en/function.implode.php
$inString= "(" . implode(",", $ids) . ")";
你会得到一个这样的字符串:(1,2,3)
.
请记住,在 SQL 查询中直接使用变量会导致 SQL 注入漏洞
推荐阅读
- java - 什么可能是最短的代码——switch Case有什么可能吗?
- javascript - WebRTC connectionState 停留在“new” - 仅适用于 Safari,适用于 Chrome 和 FF
- python - 从具有重复值的列表中理解嵌套列表
- cassandra - Cassandra 中缺少 System.log 和 Debug.log 文件
- python - “ConnectionAbortedError:[WinError 10053] 已建立的连接被主机中的软件中止”当我尝试在 db 中添加图像时
- php - 未定义变量:动作
- c# - 如何在 ASP.Net MVC C# 中将 HTML 代码传递给电子邮件
- amazon-web-services - AWS CDK -- 如何通过 AWS CDK 从我新创建的托管区域中检索我的 NS 记录
- c - 在同一地址显示数据时会出现不同的结果,具体取决于我是否使用 gdb
- bash - cat 函数未捕获整行文件