Reputation: 659
I'm trying to get some data from my object. My problem is that I would like it to be done in a foreach loop like this:
@foreach($event_types as $event_type_key => $event_type_val)
echo $data->Type.''.$event_type_key;
@endforeach
But it does not work, I get the error: Undefined property: stdClass::$Type.
In my object I have data like Type1, Type2, Type3...
And it works if I change the code to:
@foreach($event_types as $event_type_key => $event_type_val)
echo $data->Type1;
@endforeach
But I would like the type count to change with the value from the $event_types array.
Can somebody see what I am doing wrong?
Upvotes: 0
Views: 213
Reputation: 7156
Simply
@foreach($event_types as $event_type_key => $event_type_val)
echo $data->{'Type' . $event_type_key};
@endforeach
Upvotes: 1
Reputation: 33531
You want to dynamically write a PHP object property.
You do it thus:
$key = "Type1";
$data->$key;
In your case:
foreach($event_types as $event_type_key => $event_type_val):
$k = 'Type'.$event_type_key;
echo $data->$k;
endforeach
You should not use @
to suppress errors. It hides bugs.
Upvotes: 0