简体   繁体   中英

PHP: Count stdClass objects within array

I have an array with stdClass objects as below. How would I count how many I have under Interviewee_Name?

Tried counting as I would do an array but get an error that I can't becaused of the stdClass Object and then unsure how to proceed from there

Array
(
    [0] => stdClass Object
        (
            [Interviewee_Name] => Array
                (
                    [0] => stdClass Object
                        (
                            [id] => rn_Interviewee_Name_DIR_27
                            [value] => Janusz Jasinski
                        )

                )

        )

This'll get the number of elements under Interviewee_Name , but it'll count all elements, not just objects.

count($arr[0]->Interviewee_Name)

However, if you really only want to get the objects in Interviewee_Name , you'll need to array_filter the array to get only the objects, and then count that new array:

count(array_filter($arr[0]->Interviewee_Name, function ($el) {
    return (gettype($el) == 'object');
}));

The syntax for getting an element from an array looks like $arr['index'] , but in this case Interviewee_Name is a property of an object so you need to use the object syntax: $obj->prop

$array = json_decode(json_encode($formData), True);

我在添加之前添加了一个计数,然后才有效!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM