首页 > 解决方案 > 将 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 中,但我不知道如何实现。

有什么提示吗?

标签: phpmysqlarraysjsonslim

解决方案


如果我了解您需要实现的目标,您可以使用array_columnphp 函数获取 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 注入漏洞


推荐阅读