2

I am trying to forward (render) my array from php to the twig template and than print everything out in the template. My problem is to access the array in the twig template.

Php array and render function:

    while ( $row = mysqli_fetch_array ( $queryResult ) )
    {
        $tplArray = array (
                array (
                        'id' => $row ['id'] 
                ),
                array (
                        'name' => $row ['name'] 
                ) 
        );

        $tplArray = array (
                'id' => $row ['id'],
                'name' => $row ['name'] 
        );
    }

    return $this->render ( 'work/work.html.twig', array (
            'data' => $tplArray 
    ) );

Trying to access the array in the twig template:

    {% for entry in data %}
        {{ entry.id }}
        {{ entry.name }}
    {% endfor %}

This obviously do not work. How can I get the data (id, name) from my $tplArray and print it out in the template?

1 Answer 1

2

Your while loop should look like this:

$tplArray = array(); 
while ( $row = mysqli_fetch_array ( $queryResult ) )
{
    $tplArray[] = array (
         'id' => $row ['id'],
         'name' => $row ['name'] 
    );
}

With this code, you assign an empty array (as a precaution) to $tplArray first. Then, using [] operator, you push a new element - an associative array with 'id' and 'name' attributes - at each step of while loop into this resulting array.

Currently, you reassign a new array as $tplArray value at each step of while instead.

Sign up to request clarification or add additional context in comments.

1 Comment

Consider also renaming your first tplArray to something like $rows then have $tplArray = ['data' => $rows]; Using the same name for two completely different arrays makes things more confusing than they need to be. Furthermore, $rows = mysqli_fetch_all($queryResult) will eliminate your first loop completely.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.