0

因此,经过 2 小时的搜索,我似乎找不到我要找的东西。我想要做的是在数组中运行一个 foreach 循环。我知道这是不可能的,但这是我能想到的唯一方法来解释我试图做什么。所需的输出是这样的:

groups:
  fafa:
    permissions:
      worldguard.stack: true
      worldedit.biome.list: true
      worldedit.biome.set: true
Array
(
    [groups] => Array
        (
            [fafa] => Array
                (
                    [permissions] => Array
                        (
                            [worldguard.stack] => 1
                            [worldedit.biome.list] => 1
                            [worldedit.biome.set] => 1
                        )

                )

        )

)

但我似乎得到的是:

groups:
  fafa:
    permissions:
      worldguard.stack: true
Array
(
    [groups] => Array
        (
            [fafa] => Array
                (
                    [permissions] => Array
                        (
                            [worldguard.stack] => 1
                        )

                )

        )

)

请注意worldedit.biome.setandworldedit.biome.list没有出现。我知道我做错了什么,但我无法弄清楚正确的方法是什么。这是我正在做的事情:

<?php
include('spyc.php');
session_start();
$groupname = $_SESSION['gname'];
$permnode = $_POST['checkbox2'];
foreach($permnode as $perm){
$array = array (
    'groups'  => array(
        $groupname => array(
            'permissions' => array(
                $perm => true,

                )
            )
        )
);
}
$yaml = Spyc::YAMLDump($array);
echo '<pre>';
echo $yaml;
echo '</pre>';

echo '<pre>';
print_r($array);
echo '</pre>';

?>
4

1 回答 1

0

在您的代码中,您$array在每次循环迭代中一遍又一遍地覆盖数据。

$array = array('groups' => array()); // creating empty array of groups, just once
foreach($permnode as $perm){
    if (!isset($array['groups'][$groupname])) { // if the group with a particular
                                                // name doesn't exist yet

        // then creating it and initializing with empty permissions array
        $array['groups'][$groupname] = array('permissions' => array());
    }

    // here is where you was wrong: instead of overwriting the whole array
    // with new data - you're just adding another item into permissions array
    $array['groups'][$groupname]['permissions'][$perm] = true;
}
于 2013-07-20T11:22:21.517 回答