简体   繁体   中英

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. 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. $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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM