插入元件以阵列 [英] Inserting elements in an array
问题描述
我有配置树的数组:
$ CFG =阵列('全球'=>阵列(
'项目'= GT; '富',
BASE_URL'=> '/路径/',
'字符集'=> UTF-8,
'时区'=> 欧洲/里斯本,
环境= GT; 发展),
// ...
);
我需要一个元素插入到树(或可能改变它)给出的字符串,如全球:项目
和栏
,其中第一个指定的元素,第二个它的价值的路径。因此,值在
$ C>'酒吧'。 $ CFG ['全球'] ['项目']
将成为<$ C'富'
下面是功能,我需要:
函数set_cfg($路径,$值)
{/ *阿尔特$ CFG给定的设置* /}
于是我开始用爆炸路径字符串':'
并与路径键的数组:
$ PATH =爆炸(:,$ PATH)
接下来是什么?我如何定义(递归?)键的操作插入 $ CFG
数组?
函数set_cfg($路径,$值){
$ PATH =爆炸(:,$路径);
目前$ =安培; $ GLOBALS ['CFG']; //变量是全球性的,所以从$ GLOBALS得到
的foreach($为$部分路径){
目前$ =安培; $电流[$部分];
}
$目前= $价值;
}
如果你可以肯定会有永远只有两个级别的配置,你可能改用:
函数set_cfg($路径,$值){
列表($第一,第二$)=爆炸(:,$路径,2);
$ GLOBALS ['CFG'] [$首页] [$秒] = $价值;
}
I have an array with configuration tree:
$cfg = array('global' => array(
'project' => 'foo',
'base_url' => '/path/',
'charset' => 'utf-8',
'timezone' => 'Europe/Lisbon',
'environment' => 'development'),
//...
);
I need to insert an element into the tree (or possibly change it) given strings such as "global:project"
and "bar"
where first specifies a path to an element and second its value. So the value 'foo'
in $cfg['global']['project']
would become 'bar'
.
Here is the function I need:
function set_cfg($path, $value)
{ /* Alter $cfg with the given settings */ }
So I start by exploding the path string with ':'
and have an array with path keys:
$path = explode(':', $path)
What's next? How can I define (recursively?) an operation of keys insertion into the $cfg
array?
function set_cfg($path, $value) {
$path = explode(':', $path);
$current = &$GLOBALS['cfg']; // variable is global, so get from $GLOBALS
foreach ($path as $part) {
$current = &$current[$part];
}
$current = $value;
}
If you can be sure that there will be always only two levels of configuration you may instead use:
function set_cfg($path, $value) {
list($first, $second) = explode(':', $path, 2);
$GLOBALS['cfg'][$first][$second] = $value;
}
这篇关于插入元件以阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!