Foreach循环和数组问题

时间:2013-07-20 11:17:48

标签: php arrays foreach

所以经过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.setworldedit.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>';

?>

1 个答案:

答案 0 :(得分: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;
}