【问题标题】:How to save JSON objects in a array?`如何将 JSON 对象保存在数组中?`
【发布时间】:2017-12-30 18:18:23
【问题描述】:

首先,这是我正在使用的代码

$json = file_get_contents('./releases.json');
$data = json_decode($json, TRUE);
$region = isset($_GET['region']) ? $_GET['region'] : null;

# if region is not null: ?region=8
if ($region) {
    $region_filter = function($v) use ($region) {
        // 8 == Worldwide
        if ($v['region'] == $region || $v['region'] == 8) {
            return true;
        } else {
            return false;
        }
    };
    $data = array_filter($data['data'], $region_filter);
}

header('Content-Type: application/json');
echo json_encode(array('data' => $data));

如您所见,我使用 array('data' => $data) 将我的 JSON 对象 ($data) 存储在名为 'data' 的数组中,但所做的只是创建一个包含所有其他对象不是数组,我该如何解决?非常感谢!

releases.json 示例:

{
"last_update_on": "2017-12-30",
"data": [{..}, {..}]
}

【问题讨论】:

  • 我不明白这个问题。你期望的输出是什么? release.json 的结构是什么?
  • 抱歉,我编辑了我的问题
  • 假设你想要,echo json_encode($data);,否则显示你的预期输出。
  • 是的,但是您想如何解决这个问题?您期望什么结构?
  • 我想要的是 {"data":[..]} 以及我使用 ?region= 获得的新过滤数据

标签: php json


【解决方案1】:

如果未设置$_GET['region'],则跳过if 块中的代码,因此其中仍有$data['data'],然后使用array('data'=>$data) 添加另一个级别。

但是如果设置了$_GET['region'],那么if 块中的代码将删除顶层'data' 它确实是$data = array_filter($data['data'], $region_filter);

换句话说,$data 在结构上是不同的,这取决于if 块代码是否被执行。试试这个

$json = file_get_contents('./releases.json');
$data = json_decode($json, TRUE);
$data = $data['data'];
$region = isset($_GET['region']) ? $_GET['region'] : null;

# if region is not null: ?region=8
if ($region) {
    $region_filter = function($v) use ($region) {
        // 8 == Worldwide
        if ($v['region'] == $region || $v['region'] == 8) {
            return true;
        } else {
            return false;
        }
    };
    $data = array_filter($data, $region_filter);
}

header('Content-Type: application/json');
echo json_encode(array('data' => $data));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 1970-01-01
    • 2016-01-14
    相关资源
    最近更新 更多