I need to remove all nulls from this multilevel associative array. How to achieve it in PHP?
<?php
$topic = null;
$data = [
'message' => 'halo',
'image' => 'url1',
];
$jsonData = [
"to" => "/topics/".(empty($topic) ? 'customer' : $topic),
"notification" => [
"title" => null,
"body" => 'test body',
"android_channel_id" => null,
'badge' => null,
"tag" => 'tag',
],
"priority" => "high",
"data" => $data + [
'channel_key' => null,
'image' => 'url',
],
];
What I've tried:
$jsonData = myArrayFilter($jsonData);
echo json_encode($jsonData);
function myArrayFilter(&$arr, $key = null) {
if (empty($arr)) return [];
return array_filter($arr, function(&$v, $k) {
if (gettype($v) == 'array') {
$v = myArrayFilter($v, $k);
}
return isset($v);
}, ARRAY_FILTER_USE_BOTH);
}
result:
{
"to": "/topics/customer",
"notification": {
"title": null,
"body": "test body",
"android_channel_id": null,
"badge": null,
"tag": "tag"
},
"priority": "high",
"data": {
"message": "halo",
"image": "url1",
"channel_key": null
}
}
what I want:
{
"to": "/topics/customer",
"notification": {
"body": "test body",
"tag": "tag"
},
"priority": "high",
"data": {
"message": "halo",
"image": "url1"
}
}