Reshma Reshma - 2 months ago 15
Twig Question

how to display a specified value from an multidimensional array in twig template

I tried to display the service name from the array

service
. But I did not get the all names. In twig template it only shows the last entered name. Any one help me to solve this. Here is my code:

$data['service'] = array();

$sql= "SELECT * FROM services";

$serviceDetails= mysql_query($sql);

while($row = mysql_fetch_array($serviceDetails, MYSQL_ASSOC))
{

$data['service']['name'] = $row['service_name'];
$data['service']['id']= $row['service_id'];

}

echo $twig->render('test.html',$data);


In twig template,the code is,

<ul>
{% for service_name in service %}
<li>{{ service_name}}</li>
{% endfor %}
</ul>


I need to get the names only. But only last entered name is displaying.

Answer

To get both values into your twig, build $services as an array of arrays. Associative arrays tend to be the easiest to understand.

Step one, build the data structure:

$data['service'] = array();

$sql= "SELECT * FROM services";

$serviceDetails= mysql_query($sql);

while($row = mysql_fetch_array($serviceDetails, MYSQL_ASSOC))
{
    //Place both name and service_id in the array
    $data['service'][]=array('name' => $row['service_name'], 'id' => $row['service_id']);
}

echo $twig->render('test.html',$data);

Step 2: Read that data back in twig:

<ul>
    {% for  service_data in service %}
        {# service now contains both the id and name as separate elements #}
        <li>{{ service_data.id}}: {{ service_data.name}}</li>
    {% endfor %}
</ul>
Comments