2

I'm new dealing with JSONs and PHP and I'm having problems to clean out this type of array. here what I thought could work but I don't understand yet how it didn't works

for ($i = 0; $i < count($items); $i++) {
    if ($items[$i][] === null) {
        unset($items[$i]['']);
    }
}
[
    { 
        "ticketNumber": Ha&51,
        "qty": 0, 
        "title": "Wheat", 
        "price": 44.2,
        "purchaseDate": null,
        "date": null
    },
    { 
        "ticketNumber": H88i51,
        "qty": 2, 
        "title": "Prince",
        "price": 12.99,
        "purchaseDate": null,
        "date": null
    }
]
Magiczne
  • 1,586
  • 2
  • 15
  • 23
  • Are you looking for something like this? https://stackoverflow.com/questions/3654295/remove-empty-array-elements – Martin Sep 14 '20 at 18:10

2 Answers2

1

You don't need loops, just use array_filter

<?php

$array = array(1 => "PHP code tester Sandbox Online",  2 => null);
print_r($array);

$arrayFiltered = array_filter($array);
print_r($arrayFiltered);

Here's a short example

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
Vladan
  • 1,572
  • 10
  • 23
1

Here is one approach:

<?php

$s = <<<eof
[{"ticketNumber": "Ha&51","qty": 0,"title": "Wheat", "price":
44.2,"purchaseDate": null,"date": null},{        "ticketNumber": "H88i51","qty":
2, "title": "Prince", "price": 12.99,"purchaseDate": null,"date": null}]
eof;

$m_json = json_decode($s, true);
$f = fn ($v): bool => $v !== null;

foreach ($m_json as $m_tick) {
   $a[] = array_filter($m_tick, $f);
}

var_export($a);

Personally I don't like this, as you are passing values of different types to the filter function. With a strongly typed language, this wouldn't be allowed. But the alternative would be to enumerate the "good" properties, so it seemed like a good compromise in this case.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Zombo
  • 1
  • 62
  • 391
  • 407