0

我的数组“$groupData”如下所示:

 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}},但它不起作用。

4

1 回答 1

0

您的问题是{{ . }}...您正在尝试将关联数组呈现为字符串,而这在 PHP 中不起作用:

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

像 Mustache 的大多数事情一样,这里的答案是准备好你的观点。您究竟希望它将该数组呈现为什么?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);
于 2014-03-24T18:54:40.513 回答