0

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

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 example:

{
"last_update_on": "2017-12-30",
"data": [{..}, {..}]
}
7
  • 1
    I don't understand the question. What is the output you expect? What is the structure of releases.json? Commented Dec 30, 2017 at 18:30
  • Sorry about that, I edited my question Commented Dec 30, 2017 at 18:33
  • Presume you want, echo json_encode($data);, else show your expected output. Commented Dec 30, 2017 at 18:35
  • Yes, but how you want to fix this? What structure would you expect? Commented Dec 30, 2017 at 18:36
  • What I want is {"data":[..]} with the new filtered data I get with ?region= Commented Dec 30, 2017 at 18:37

1 Answer 1

0

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).

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

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.