PHP: Accessing an object property with a variable
Let's assume I have an array of object properties I'd like to access:
$properties = array('foo', 'bar');
I'd like to loop through the object and access these properties dynamically (specifically, I'm trying to dynamically handle missing JSON elements based on an array of expected elements):
foreach ($data as $item) {
foreach ($properties as $property) {
if (empty($item->{$property})) {
// Do something
}
}
}
Each $item in $data should have the properties 'foo' and 'bar'. I'm handling the cases where 'foo' or 开发者_运维知识库'bar' doesn't exist.
I'm trying to get the loop (in line 3) to access $item->{'foo'} and $item->{'bar'}, but it's not working.
Any idea why? I'm fairly certain it's a matter of syntax, but obviously I haven't been able to figure this out!
Thanks!
Could you not use property_exists($item, $property)
.
foreach ($data as $item) {
foreach ($properties as $property) {
if ( property_exists($item, $property) ) {
// Do something
}
}
}
If what you're doing involves modifying the original set of items, keep in mind that foreach
operates on a copy of the original array. If you want to modify things in the original array, you'll need to use something like foreach($arr as $k => $v)
syntax, then modify $arr[$k]
.
I figured it out...
I think I was working on the wrong portion of the object.
Thanks for the informative answers!
精彩评论