0

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"
  }
}
Taufik Nur Rahmanda
  • 1,862
  • 2
  • 20
  • 36
  • 1
    I think this has been answered a few different times, so you should be able to find something already out there, for example you could try this answer from @mickmackusa https://stackoverflow.com/a/44006898/1712345 – treckstar Jun 10 '22 at 02:55
  • Here is a good (abused) answer: https://stackoverflow.com/a/46755701/2943403 – mickmackusa Jun 10 '22 at 03:02
  • You don't need recursion, but this question has the same data structure and requirement: https://stackoverflow.com/q/70197217/2943403 – mickmackusa Jun 10 '22 at 03:06
  • 1
    @Tau how about this rethink: https://3v4l.org/HcMP3 It appears that your data structure doesn't need recursion because it is never deeper than two levels. This also removes empty first level arrays as they are potentially created during filtering. – mickmackusa Jun 10 '22 at 04:01

0 Answers0