0

I have this array:

$arr = array(
    'reportDescription' => array(
        'reportSuiteID' => 'globretailprod',
        'elements' => array(
            0 => array(
                'id' => $queryElement
            )
        ),
        'metrics' => array(
            0 => array(
                'id' => $queryMetric
            )
        )
    )
);

I'm trying to insert some code into the array using an if command. This is what I have:

if (isset($querySegment)) {
    $arr['reportDescription']['segments'] = $querySegment;
}

However that gives me the wrong result, what I am trying to achieve is this:

{
                "reportDescription": {
                                "reportSuiteID": "rbsglobretailprod",
                                "dateFrom": "2018-09-09",
                                "dateTo": "2018-09-10",
                                "dateGranularity": "day",
                                "metrics": [{
                                                "id": "pageviews"
                                }],
                                "elements": [{
                                                "id": "page"
                                }],
                                "segments": [{
                                                "id": "jjj"
                                }]
                }
}

Notice there are two issues with this. Firstly, segments isn't isn't insert with an id, it's just inserted as a value. Secondly, I am a bit concerned about the trailing comma after metrics in my original array, since I need to be able to add a comma after the metrics array if I do include segments.

3
  • 1
    Use $arr['reportDescription']['segments'] = ["id" => $querySegment] Commented Oct 6, 2018 at 9:50
  • "Firstly, segments isn't isn't insert with an id, it's just inserted as a value" -> what do you mean by this? The JSON representation of an array will not show indices. If you want it as an object, you can use the JSON_FORCE_OBJECT option of json_encode. Commented Oct 6, 2018 at 9:55
  • Please state what your code outputs, so we can compare with what you want to accomplice Commented Oct 6, 2018 at 9:57

1 Answer 1

1

Just use the same format as you use for the other items to get the same structure...

if (isset($querySegment)) {
    $arr['reportDescription']['segments'] = array(
            0 => array(
                'id' => $querySegment
            )
        );
}

As for the comma, this should be added automatically as needed if your using json_encode()

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.