Count True values in an Object

Asked

Viewed 58 times

0

I got this feedback 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’d like to count how many projects have the key completed => true, how can I do this?

Example:

if ( $objeto->completed == true )
{
  $contar++;
}
  • Doesn’t it work? What’s the problem? Tried $objeto->data->completed ?

1 answer

0


Just make a loop and count the items, with the foreach you can. See how it turned out:

<?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.

  • Notice: Trying to get Property of non-object in: Note: I have tried changing $item->completed to $item['completed']

  • @Mustacheweb, this code must be inside the foreach. In your example I do not know the name of the variable that is all data, but assuming it is $dates, to access a direct item would be: $dates->data->{'44'}->completed. Note: To work this way, the class must be native or inherited from stdClass.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.