We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Associative array in volt

I have this code:

{% for row in table_rows %}
    <tr>
        {% for field in table_fields %}
            <td>
                <?php echo $row[$field] ?>
            </td>
        {% endfor %}    
    </tr>
{% endfor %}

How do I convert <?php echo $row->$field; ?> into something like {{ row[field] }} or {{ row.field }}? Of course the latter doesn't work.

Check this out : https://docs.phalcon.io/en/latest/db-models#hydration-modes ,

Also check out toArray() method in model.

{{ row[field] }} is the correct way to access array properties, {{ row.field }} this is for object properties. Have you tried with the first way?

What type are table_rows and table_fields? I guess table_rows is array of objects, if so you can try converting it to array with ->toArray() before passing to volt, as @Mohsin suggested.



1.8k
edited Jun '18

Hi guys. Thanks for showing me the way. Apparently table_rows is the result of Phalcon\Paginator\Adapter\Model->getPaginate() and does not have the ->toArray() method. I ended up using json_decode(json_encode(table_rows), true) method.

edited Jun '18

If you generated the pagination results using the result of find() or findFirst() or from a QueryBuilder, getPaginate() returns a ResultSet, which can be iterated like an array without needing to explicitly convert it to an array. $row should be a model, which does have a toArray() method. So this should work:

{% for row in table_rows %}
    <tr>
        {% for field in table_fields %}
            <?php $arrayRow = $row->toArray(); ?>
            <td>
                <?= $row[$field] ?>
            </td>
        {% endfor %}    
    </tr>
{% endfor %}

I wouldn't be to worried about eliminating raw PHP code from your templates. Sometimes it's just easier to use raw PHP than Volt, and Volt gets transpiled to PHP anyway, so there's really no harm.