[英]Unable to set the value of multidimensional array by key
I have an static array property 我有一个静态数组属性
private static $config = array(
'base_url' => '',
'environment' => '',
'database' => array(
'dbdriver' => '',
'dbhost' => '',
'dbname' => '',
'dbuser' => '',
'dbpass' => ''
),
'default_controller' => ''
);
There is a static method to set the value of items by key 有一个静态方法可以通过键设置项目的值
public static function set($key, $value)
{
if(isset(self::$config[$key]))
self::$config[$key] = $value;
else
{
foreach (self::$config as $i => $j)
{
if(!is_array($j))
continue;
foreach ($j as $k => $v)
{
if($k == $key)
{
$j[$k] = $value;
break;
}
}
}
}
}
Now this works in case of base_url, environment etc. But when i am doing Config::set('dbdriver', 'PDO')
it is not working. 现在,这在base_url,环境等情况下有效。但是,当我在执行Config::set('dbdriver', 'PDO')
它将无法正常工作。 Also i am not sure how to handle it if the nested array goes more deep. 另外,如果嵌套数组变得更深,我不确定如何处理它。
Please help me fixing this issue or i would welcome any good solution also. 请帮助我解决此问题,否则我也欢迎任何好的解决方案。
Thanks 谢谢
This is because when you are inside the foreach
you are given copies of the values. 这是因为当您进入foreach
,将获得值的副本 。 $j[$k] = $value;
doesn't update the main array, as you see. 如您所见,它不会更新主数组。
You need to use references to make sure the original array gets updated. 您需要使用引用来确保原始数组得到更新。
// The `&` makes $j into a reference
foreach (self::$config as $i => &$j){
if(!is_array($j)){
continue;
}
// You don't actually need to use a `foreach` here
// You can just check if the key is set
if(isset($j[$key])){
// This should update the main array
$j[$key] = $value;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.