After loading TWIG, add this filter:
$twig->addFilter( new Twig_SimpleFilter('cast_to_array', function ($stdClassObject) {
$response = array();
foreach ($stdClassObject as $key => $value) {
$response[] = array($key, $value);
}
return $response;
}));
It's named cast_to_array after Tadeck's suggestion. :)
I'm sure it doesn't work for any kind of stdClass Object, but it sure solved my problem with printing PHP associative arrays :) Use it as follows:
{% for key, value in my_object|cast_to_array %}
<td>{{ value.1 }}</td>
{% endfor %}
Side story
Since I got into this SO page a lot, I think it's pertinent to show where I'm using Twig for iterating over object properties, so it's helpful for other people with the same problem:
I was trying to print a table from a .json source, but PHP's json_decode transforms any "key" : "value" into a PHP associative array, which Twig doesn't print by default.
So this filter cuts and delivers a regular array to be used by Twig.
source.json
{
"user": {
"family": {
"table": [{
"First_Name": "John",
"Last_Name": "Foo",
"Age": 25,
"Role": "Brother"
}, {
"First_Name": "Mary",
"Last_Name": "Bar",
"Age": 14,
"Role": "Sister"
}, {
"First_Name": "Joe",
"Last_Name": "Baz",
"Age": 33,
"Role": "Uncle"
}]
}
}
}
Twig
<table>
<thead>
<tr> {# get table headers from the table row #}
{% for row in user.family.table.0|cast_to_array %}
<th>{{ row.0 | replace({'_': ' '}) }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for row in user.family.table %}
<tr>
{% for key, value in row|cast_to_array %}
<td>{{ value.1 }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>