我如何循环遍历树枝数据

时间:2016-05-07 22:22:40

标签: php loops twig render frontend

我的树枝有问题。

这是我在数据库中的数组:

databaseData array(3) {
  ["name"]=>
  array(10) {
    [0]=>
    string(14) "item0"
    [1]=>
    string(13) "item1"
    [2]=>
    string(13) "item2"
    [3]=>
    string(14) "item3"
    [4]=>
    string(17) "item4"
    [5]=>
    string(13) "item5"
    [6]=>
    string(12) "item6"
    [7]=>
    string(9)  "item7"
    [8]=>
    string(12) "item8"
    [9]=>
    string(6)  "item9"
  }
  ["amount"]=>
  array(10) {
    [0]=>
    string(2) "20"
    [1]=>
    string(2) "20"
    [2]=>
    string(2) "20"
    [3]=>
    string(2) "20"
    [4]=>
    string(2) "20"
    [5]=>
    string(2) "20"
    [6]=>
    string(2) "20"
    [7]=>
    string(2) "20"
    [8]=>
    string(2) "20"
    [9]=>
    string(2) "20"
  }
  ["path"]=>
  array(10) {
    [0]=>
    string(26) "/images/item0.png"
    [1]=>
    string(25) "/images/item1.png"
    [2]=>
    string(25) "/images/item2.png"
    [3]=>
    string(26) "/images/item3.png"
    [4]=>
    string(29) "/images/item4.png"
    [5]=>
    string(25) "/images/item5.png"
    [6]=>
    string(24) "/images/item6.png"
    [7]=>
    string(21) "/images/item7.png"
    [8]=>
    string(18) "/images/item8.png"
    [9]=>
    string(18) "/images/item9.png"
  }
}

这就是我把它传递给树枝的方式:

$data['name'] = $this->factory->createHomeController()->allNamesFromDatabase);
            $data['amount'] = $this->factory->createHomeController()->allAmountsFromDatabase();
            $data['path'] = $this->factory->createHomeController()->allImagePathsFromDatabase();

return $this->twigEnv->render('index.twig', array(
               'data' => $databaseData,
               ));
index.twig中的

我想在一个""

中显示图片,数量和名称
{% for item in data['path'] %}
{% for item0 in data['name'] %}
    <img class="" src="{{ item }}" alt="" height="200" width="200">
    <h1>{{ name }}</h1>
{% endfor %}
{% endfor %}

我尝试了很多,但仍然无法弄清楚我是如何解决这个问题的:(

如果有人可以帮助我会很好:)

2 个答案:

答案 0 :(得分:2)

你可以通过以下方式模仿树枝中的foreach ($data as $key => $value) { .. }

  {% for index,path in data.path %}
    <img class="" src="{{ path }}" alt="" height="200" width="200" />
    <h1>{{ data.name[index] }}</h1>
  {% endfor %}

答案 1 :(得分:1)

尝试这种方式:

  {% for path in data.path %}
    <img class="" src="{{ path }}" alt="" height="200" width="200">
  {% endfor %}

  {% for name in data.name %}
    <h1>{{ name }}</h1>
  {% endfor %}