I would like to output a JSON string with an optional fields.
Right now I do it as simple as:
echo json_encode(array(
'qwe' => 1,
'asd' => 2,
'zxc' => 3
));
Now, say, I would like to include/exclude the 'asd' element based on some logic (using an inline if or some function or something else).
I have no idea how to do it, because, AFAIK, there is no such type in PHP that can force json_encode to skip this field - everything returns null or empty fields but does not skip the field itself.
Any ideas someone?
do you mean something like this:
$arr = array(
array(
'qwe' => 1,
'asd' => 2,
'zxc' => 3
),
array(
'qwe' => 4,
'asd' => '',
'zxc' => 6
)
);
foreach ($arr as $key => $row) {
if ($row['asd'] == '') {
unset($arr[$key]['asd']);
}
}
echo json_encode($arr);