【问题标题】:looping through two dimensional array and passing to mustache template循环遍历二维数组并传递给 mustache 模板
【发布时间】:2015-02-06 08:32:55
【问题描述】:

所以我刚刚开始使用 mustache.php,但我一直在尝试循环二维数组。我有一个看起来像这样的数组...

 $FeedArray = array(3) { [0]=> array(3) { ["entity"]=> string(10) "mail" 
                                          ["time"]=> string(19) "2015-02-05 05:10:26"
                                          ["title"]=> string(0) "what's up?" }         
                         [1]=> array(3) { ["entity"]=> string(5) "event" 
                                          ["time"]=> string(19) "2015-02-05 03:16:54"
                                          ["title"]=> string(15) "asfasggasdgasdg"  } 
                         [2]=> array(3) { ["entity"]=> string(10) "mail"
                                          ["time"]=> string(19) "2015-01-11 14:24:08"
                                          ["title"]=> string(24) "lunch?" } }

我正在尝试这样循环:

$eventTemplate = file_get_contents('templates/GroupPageEvent.mustache');
$postTemplate = file_get_contents('templates/GroupPagePost.mustache');

       foreach ($FeedArray as $entity => $row){

              if ($row['entity_type']=='mail'){
                     echo $m->render($postTemplate, $entity);
              }

              if ($row['entity_type']=='event'){
                     echo $m->render($eventTemplate, $entity); 
              }

       }

我知道我的模板运行良好。只是没有正确传递子数组($entity),所有输出的模板都是空的。

if $row['entity_type'}==? 也可以正常读取。

任何帮助表示赞赏。

【问题讨论】:

  • 您定义了entry,但读取了entry_type。将$row['entity_type'] 更改为$row['entity']
  • 无关:如果您将模板解析移到 foreach 循环之外,您将获得更好的性能。将前两行更改为:$eventTpl = $m->loadTemplate(file_get_contents(...)) 并将循环内的调用更改为 echo $eventTpl->render($entity)
  • @bobthecow...非常感谢。我会试一试。

标签: php arrays mustache mustache.php


【解决方案1】:

这是因为您将密钥传递给您的渲染函数,$entity 包含数组密钥 (0,1,2...),而您的实体数组存储在 $row

foreach ($FeedArray as $entity => $row){

在这种情况下,你应该这样做:

echo $m->render($postTemplate, $row);

而且在数组中你得到的是 'entity' 键而不是 'entity_type' 所以也改变这个:

$row['entity_type']=='mail'

到:

$row['entity']=='mail'

【讨论】:

    猜你喜欢
    • 2014-12-22
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 2018-03-09
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 2021-11-03
    相关资源
    最近更新 更多