如何在树枝模板

时间:2016-09-02 10:29:17

标签: php arrays twig

我尝试显示数组service中的服务名称。但我没有得到所有的名字。在树枝模板中,它仅显示最后输入的名称。任何人都帮我解决这个问题。这是我的代码:

$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);

在twig模板中,代码为

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

我只需要获取名字。但只显示最后输入的名称。

2 个答案:

答案 0 :(得分:0)

在PHP中每次循环传递都会覆盖数组Map<MyEnum, MyObject> 。我不太确定你想看到什么,但我希望如果你把PHP改成这个,那么这个小枝就会起作用:

$data['service']

答案 1 :(得分:0)

要将两个值都放入树枝中,请将$services构建为数组。关联数组往往是最容易理解的。

第一步,构建数据结构:

$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);

第2步:在树枝上读回数据:

<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>