I have an object $obj that’s the result of json_encode, with a structure similar to this:
stdClass Object (
[page] = 1
[size] = -1
[total] = 4
[collection] = Array
(
[0] = stdClass Object
(
[id] = 4e87de8e1a8840999f907fad
[description] = ffffffff
[code] = 82666
[status] = ACTIVE
)
[1] = stdClass Object
(
[id] = 4e8b4b53fda5efeeec370e89
[description] = gggggggggg
[code] = 41874
[status] = ACTIVE
)
[2] = stdClass Object
(
[id] = 4e8b4b5afda5efeeec370e8a
[description] = hhhhhhhhhhhhh
[code] = 15130
[status] = ACTIVE
)
[3] = stdClass Object
(
[id] = 4e90a753e91a2713c95b56a0
[description] = jjjjjjjjjjjjjj
[code] = 323307
[status] = ACTIVE
)
[4] = stdClass Object
(
[id] = 4e9e08da79597f0d3daba159
[description] = kkkkkkkkkkkkkk
[code] = 11310
[status] = ACTIVE
)
) )
I have a value $code and want to search in $obj->collection, setting $id = to the id property of the object whose code property is equal to the value of $code. I’m doing this now with a conditional loop that checks the code property of each and sets $id if true, but I’m thinking there may be a command I’m missing out on due to being fairly unfamiliar with OO PHP.
Any way I could improve on this?
Let me open with this:
stdClasshas no advantage over arrays (beside the fact it may “look cool”). It is in fact not OOP. To use arrays instead ofstdClasses, havetrueas the second parameter tojson_decode():Will return an array.
Other than that, iterating and checking for $code seems like the way to go. There’s no PHP function to do that for you (thank God). Arrays however have the distinct advantage of being able to be manipulated by array functions, (not to mention the efficiency boost).