Count True Values on an Object

0

I have this return from an API:

object(stdClass)[2]
  public 'data' => 
    object(stdClass)[44]
       public 'id' => float 3.5795374673835E+14
       public 'completed' => boolean false
       public 'name' => string 'Dia dos Namorados' (length=17)

And I would like to count how many projects are with the completed => true key, how can I do that?

Example:

if ( $objeto->completed == true )
{
  $contar++;
}
    
asked by anonymous 12.06.2017 / 17:27

1 answer

0

Just loop and count the items, with the foreach you can. Here's how it went:

<?php

$object = (object) array(
    'data' => (object) array(
        44 => (object) array(
           'id' => 3.5795,
           'completed' => false,
           'name' => 'Lorem ipsum dolor.',
        ),
        45 => (object) array(
           'id' => 3.5796,
           'completed' => false,
           'name' => 'Lorem ipsum dolor.',
        ),
        46 => (object) array(
           'id' => 3.5797,
           'completed' => true,
           'name' => 'Lorem ipsum dolor.',
        ),
        47 => (object) array(
           'id' => 3.5798,
           'completed' => false,
           'name' => 'Lorem ipsum dolor.',
        ),
    )
);

$countTrue = 0;
$countFalse = 0;

foreach($object->data as $item)
{
    if($item->completed){
        $countTrue ++;
    } else {
        $countFalse++;
    }

}

echo "Itens como true: " . $countTrue; // 1
echo "Itens como false: " . $countFalse; // 3

?>

Example Ideone .

    
12.06.2017 / 18:09