Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>After loading TWIG, add this filter:</p> <pre><code>$twig-&gt;addFilter( new Twig_SimpleFilter('cast_to_array', function ($stdClassObject) { $response = array(); foreach ($stdClassObject as $key =&gt; $value) { $response[] = array($key, $value); } return $response; })); </code></pre> <p>It's named <strong>cast_to_array</strong> after <a href="https://stackoverflow.com/users/548696/tadeck">Tadeck</a>'s suggestion. :) I'm sure it doesn't work for any kind of <em>stdClass Object</em>, but it sure solved my problem with printing PHP <em>associative arrays</em> :) Use it as follows:</p> <pre><code>{% for key, value in my_object|cast_to_array %} &lt;td&gt;{{ value.1 }}&lt;/td&gt; {% endfor %} </code></pre> <h1>Side story</h1> <p>Since I got into this SO page a lot, I think it's pertinent to show where I'm using Twig for <em>iterating over object properties</em>, 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 <em>"key" : "value"</em> 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.</p> <h2>source.json</h2> <pre><code>{ "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" }] } } } </code></pre> <h2>Twig</h2> <pre><code>&lt;table&gt; &lt;thead&gt; &lt;tr&gt; {# get table headers from the table row #} {% for row in user.family.table.0|cast_to_array %} &lt;th&gt;{{ row.0 | replace({'_': ' '}) }}&lt;/th&gt; {% endfor %} &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; {% for row in user.family.table %} &lt;tr&gt; {% for key, value in row|cast_to_array %} &lt;td&gt;{{ value.1 }}&lt;/td&gt; {% endfor %} &lt;/tr&gt; {% endfor %} &lt;/tbody&gt; &lt;/table&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload