2014-03-24 59 views
0

我的數組「$ groupData」看起來是這樣的:渲染陣列中的PHP數組中的小鬍子

array(3) (
    0 => array(3) (
     "id" => string(1) "2" 
     "name" => string(20) "Super Administrators" 
     "permissions" => array(3) (
      "system" => integer 1 
      "superuser" => string(1) "1" 
      "admin" => string(1) "1" 
     ) 
    ) 
    1 => array(3) (
     "id" => string(1) "3" 
     "name" => string(10) "Publishers" 
     "permissions" => array(4) (
      "system.pub.add" => integer 1 
      "system.pub.delete" => integer 1 
      "system.pub.edit" => integer 1 
      "system.pub.publish" => integer 1 
     ) 
    ) 
    2 => array(3) (
     "id" => string(1) "4" 
     "name" => string(7) "Authors" 
     "permissions" => array(3) (
      "system.pub.add" => integer 1 
      "system.pub.delete" => integer 1 
      "system.pub.edit" => integer 1 
     ) 
    ) 
) 

我無法使我的代碼permissions部分。我曾嘗試使用{{#groupData}}{{#permissions}} {{.}} {{/permissions}}{{/groupData}},但它不起作用。

回答

0

您的問題是{{ . }} ...你試圖呈現一個關聯數組作爲一個字符串,而只是沒有在PHP工作:

<?php 
echo array('foo' => 1, 'bar' => 2); // no me gusta :) 

最喜歡的事情小鬍子,這裏的答案是準備你的觀點。你究竟期待它將該數組渲染爲? JSON?如果是這樣,使其明確:

<?php 
foreach ($data['groupData'] as $key => $group) { 
    $data['groupData'][$key]['permissionsJSON'] = json_encode($group['permissions']); 
} 

$tpl = "{{# groupData }}{{ permissionsJSON }}{{/ groupData }}"; 

$m = new Mustache_Engine; 
echo $m->render($tpl, $data); 

如果你希望它可以作爲對鍵/值,這樣做明確:

<?php 
foreach ($data['groupData'] as $key => $group) { 
    $permissions = array(); 
    foreach ($group['permissions'] as $key => $val) { 
     $permissions[] = array('key' => $key, 'val' => $val); 
    } 
    $data['groupData'][$key]['permissions'] = $permissions; 
} 

$tpl = "{{# groupData }}{{# permissions }}{{ key }}: {{ val }}{{/ permissions }}{{/ groupData }}"; 

$m = new Mustache_Engine; 
echo $m->render($tpl, $data); 

你只是想遍歷鍵的列表?

<?php 
foreach ($data['groupData'] as $key => $group) { 
    $data['groupData'][$key]['permissions'] = array_keys($group['permissions']); 
} 

$tpl = "{{# groupData }}{{# permissions }}{{ . }}{{/ permissions }}{{/ groupData }}"; 

$m = new Mustache_Engine; 
echo $m->render($tpl, $data); 
+1

更改我的代碼並使用鍵/值部分。奇蹟般有效。 – Churchill