Home > OS >  Append string to JSON only if a variable is set
Append string to JSON only if a variable is set

Time:08-29

I have a json array: $json = [];

Then in a loop I add data to it, and these fields have nested structure:

$json[] = [
   "key1" => "value1",
   "key2" => array(
       "key3" => "value3",
       "key4" => "value4",                   
       "foo" => $bar 
    )
];

How can I add the key foo only if $bar is set, otherwise not add it at all?

The following doesn't work:

$json[] = [
   "key1" => "value1",
   "key2" => array(
       "key3" => "value3",
       "key4" => "value4",                   
       "foo" => $bar ?? null 
    )
];

$bar is also an array if that matters

CodePudding user response:

Here's an example code for conditionally adding $bar to json['key2']['foo']:

// some loop
while (true) {
    $bar = []; // set bar to array or null

    $key2 = [
        "key3" => "value3",
        "key4" => "value4"
    ];

    if (isset($bar)) { // or empty($bar)
        $key2['foo'] = $bar;
    }

    $json[] = [
        "key1" => "value1",
        "key2" => $key2
    ];
}
  •  Tags:  
  • php
  • Related