-1

I am trying to filter out empty entries in an object.

For example an object like this:

stdClass Object
(
    [maten0] => stdClass Object
        (
            [XXS] => 
            [XS] => 
            [S] => 10
            [M] => 10
            [L] => 
            [XL] => 
            [XXL] => 
        )

)

The desired output would be:

stdClass Object
(
    [maten0] => stdClass Object
        (
            [S] => 10
            [M] => 10
        )

)

I create the object with json. Like so:

$kuubobject = json_decode($artikel['aantalkuub']);

I found out how to do this with arrays but the following does not work for objects:

$filteredobject = array_filter($kuubobject, 'strleng');

This gives me the error:

array_filter() expects parameter 1 to be array, object given

How can I do this with objects?

I've tried the following after the marked duplicate question:

$object = (object) array_filter((array) $kuubobject);
echo '<pre>';
print_r($object);
echo '</pre>';

But I get the same output as above.

twan
  • 2,450
  • 10
  • 32
  • 92
  • Why not `$kuubobject = json_decode($artikel['aantalkuub'], true);` and then you be able to use `array_filter` – dWinder May 21 '19 at 11:32

1 Answers1

0

You can use array_filter

$filteredobject  = array_filter((array)$object->maten0);
Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20
  • Thanks but `maten0` can be different anytime so adding it like this will not work for all my objects. Another page can have `maten1` for example. – twan May 21 '19 at 11:54
  • if it's different then you can `foreach` and use `$object->{$key}` – Rakesh Jakhar May 21 '19 at 11:56