如何从YAML获取和使用关联数组到Symfony中的操作?

时间:2023-01-15 11:08:57

Ive got in app.yml some configration data, and I want to foreach them in action. I try do this by get them by sfConfig::get('app_datas') but it fails. Lets show them in details:

我已经在app.yml中获得了一些移民数据,我想在行动中预告他们。我尝试通过sfConfig :: get('app_datas')获取它们,但它失败了。让我们详细说明:

YAML:

YAML:

all:
  datas:
    foo: bar
    foo2: bar2

and in the actions.class.php I try use this code:

并在actions.class.php中我尝试使用此代码:

foreach (sfConfig::get('app_datas') as $key => $value) {

    echo "key $key has value $value";

}

it doesnt work because sfConfig::get('app_datas') is NULL, how simly get it?

它不起作用,因为sfConfig :: get('app_datas')是NULL,怎么模拟得到它?

2 个解决方案

#1


9  

When Symfony loads app.yml config files, it only stores the 2nd level down. So you can't access app_datas directly. If you want to get an array containing foo and foo2, make a YAML file like:

当Symfony加载app.yml配置文件时,它只会存储第二级。因此您无法直接访问app_datas。如果要获取包含foo和foo2的数组,请创建一个YAML文件,如:

all:
  datas:
    baz:
      foo: bar
      foo2: bar2

You can then do sfConfig::get('app_datas_baz') which will be an array containing foo and foo2 as keys.

然后你可以做sfConfig :: get('app_datas_baz'),它将是一个包含foo和foo2作为键的数组。

On Edit: kuba's way is better than a dummy; forgot you could do that.

编辑:库巴的方式比假人更好;忘记你可以那样做。

#2


15  

If you want to access first level as an array you can introduce dummy level in between, just like @jeremy suggested. Prefix it with a dot if you don't want it to actually appear in config the variable names:

如果你想作为一个数组访问第一级,你可以在它们之间引入虚拟级别,就像@jeremy建议的那样。如果您不希望它实际出现在配置变量名称中,请用点加前缀:

all:
  .baz:
    datas:
      foo: bar
      foo2: bar2

Now you should be able to access your data with:

现在,您应该可以使用以下方式访问您的数据:

foreach (sfConfig::get('app_datas') as $key => $value) 
{
  echo "key $key has value $value";
}

#1


9  

When Symfony loads app.yml config files, it only stores the 2nd level down. So you can't access app_datas directly. If you want to get an array containing foo and foo2, make a YAML file like:

当Symfony加载app.yml配置文件时,它只会存储第二级。因此您无法直接访问app_datas。如果要获取包含foo和foo2的数组,请创建一个YAML文件,如:

all:
  datas:
    baz:
      foo: bar
      foo2: bar2

You can then do sfConfig::get('app_datas_baz') which will be an array containing foo and foo2 as keys.

然后你可以做sfConfig :: get('app_datas_baz'),它将是一个包含foo和foo2作为键的数组。

On Edit: kuba's way is better than a dummy; forgot you could do that.

编辑:库巴的方式比假人更好;忘记你可以那样做。

#2


15  

If you want to access first level as an array you can introduce dummy level in between, just like @jeremy suggested. Prefix it with a dot if you don't want it to actually appear in config the variable names:

如果你想作为一个数组访问第一级,你可以在它们之间引入虚拟级别,就像@jeremy建议的那样。如果您不希望它实际出现在配置变量名称中,请用点加前缀:

all:
  .baz:
    datas:
      foo: bar
      foo2: bar2

Now you should be able to access your data with:

现在,您应该可以使用以下方式访问您的数据:

foreach (sfConfig::get('app_datas') as $key => $value) 
{
  echo "key $key has value $value";
}