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

treyBake
  • 6,440
  • 6
  • 26
  • 57
Jimmy
  • 12,087
  • 28
  • 102
  • 192
  • 1
    Remove the `if` statement. After you declare your array add something like `if ($queryType == "realtime") { $arr['source'] = 'realtime'; }` – Darragh Enright Oct 01 '18 at 12:39
  • Maybe use it as https://stackoverflow.com/questions/1506527/how-do-i-use-the-ternary-operator-in-php-as-a-shorthand-for-if-else – Koen Hollander Oct 01 '18 at 12:39

1 Answers1

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';
}
Mikey
  • 2,606
  • 1
  • 12
  • 20