0

This is a bit of an odd one. I am building an array in PHP and then encoding it to JSON before I spit it out.

$arr = array (
  'reportDescription' => 
  array (
    if ($queryType == "realtime") 
    {
        'source' => 'realtime',
    }
    'reportSuiteID' => 'rbsglobretailprod',
    'dateGranularity' => $queryGran,
    'dateFrom' => $queryFrom,
    'dateTo' => $queryTo,
    'elements' => 
    array (
      0 => 
      array (
        'id' => $queryElement,
      ),
    ),
    'metrics' => 
    array (
      0 => 
      array (
        'id' => $queryMetric,
      ),
    ),
  ),
);

I am trying to get it to add a line to the array if the query type is realtime. This is what I tried but I'm not sure if it's possible to do this, and if it's not, I'm not sure how I should approach it. The error I get below suggests it may not be possible:

Parse error: syntax error, unexpected 'if' (T_IF), expecting ')'

2
  • 1
    Remove the if statement. After you declare your array add something like if ($queryType == "realtime") { $arr['source'] = 'realtime'; } Commented Oct 1, 2018 at 12:39
  • Maybe use it as stackoverflow.com/questions/1506527/… Commented Oct 1, 2018 at 12:39

1 Answer 1

5

You should do it as two separate calls:

$array = ['your', 'array', 'with', 'fields']
if ($queryType === 'realtime') {
    $array[] = ['source' => 'realtime'];
}

Obviously change out the values with your expected values, but that should do the job. You could also append like so if you wanted it at root level:

if ($queryType === 'realtime') {
    $array['source'] = 'realtime';
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.