如何将JSON对象保存在数组中? [英] How to save JSON objects in a array?`

查看:112
本文介绍了如何将JSON对象保存在数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

First of all, here's the code I'm using

$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'的数组中,但是所有要做的就是创建一个包含所有内容的父对象数据其他对象不是数组,我该如何解决?非常感谢你!

As you can see I'm using array('data' => $data) to store my JSON objects ($data) in array named 'data', but all this do is create a parent object data that has all the other objects not an array, how can i fix this? Thank you very much!

releases.json示例:

releases.json example:

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

推荐答案

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

If $_GET['region'] is not set, then you skip the code within the if block and so still has $data['data'] in it and then you add another level with array('data'=>$data).

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

But if $_GET['region'] is set, then the code within the if block will remove the top level 'data' it does $data = array_filter($data['data'], $region_filter);.

换句话说,根据是否执行if块代码,$data在结构上有所不同.试试这个

In other words, $data is structurally different depending on if the if block code is executed or not. Try this

$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));

这篇关于如何将JSON对象保存在数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆