【问题标题】:Why is my preferences data being returned as an array instead of a string?为什么我的首选项数据以数组而不是字符串的形式返回?
【发布时间】:2017-01-02 10:31:11
【问题描述】:

我正在使用这个 Config 类来让我更容易地读出我的偏好。

<?php

class Config {
    public static function get($path = null) {
        if ($path){
            $config = $GLOBALS['config'];
            $path = explode('/', $path);

            foreach($path as $bit) {
                if(isset($config[$bit])) {
                    $config = $config[$bit]; 
                }
            }

            return $config;
        }

        return false;
    }
}

现在,我应该能够通过在我的脚本中使用这一行来获取配置:

echo Config::get('settings/main_color');

我的首选项位于 JSON 文件中,但存储在 $GLOBALS['config'] 中的数组如下所示:

Array ( 
    [mysql] => Array ( 
        [host] => localhost:3307 
        [username] => root 
        [password] => usbw 
        [db] => webshop )
    [remember] => Array ( 
        [cookie_name] => hash 
        [cookie_expiry] => 604800 ) 
        [sessions] => Array ( 
        [session_name] => user 
        [token_name] => token ) 
    [settings] => Array ( 
        [main_color] => #069CDE 
        [front_page_cat] => Best Verkocht,Populaire Producten 
        [title_block_first] => GRATIS verzending van €50,- 
        [title_block_second] => Vandaag besteld morgen in huis! ) 
    [statics] => Array ( 
        [header] => enabled 
        [title_block] => enabled 
        [menu] => enabled 
        [slideshow] => enabled 
        [left_box] => enabled 
        [email_block] => enabled 
        [footer] => enabled 
        [keurmerken] => enabled 
        [copyright] => enabled ) 
)

现在,当我尝试在我的脚本中访问一个首选项时。它说我的字符串是一个数组。所以我用 print_r 来显示数组。那么结果如下:

print_r(Config::get('settings/main_color'));

Array ( [header] => 启用 [title_block] => 启用 [menu] => 启用 [slideshow] => 启用 [left_box] => 启用 [email_block] => 启用 [footer] => 启用 [keurmerken] => 启用 [版权] => 启用)

我的脚本哪里出错了?

【问题讨论】:

  • 检查你的get方法,肯​​定错了

标签: php arrays string oop data-conversion


【解决方案1】:

如果确实如此,您的数组是结构化的,如上所示,这应该可以工作

<?php

class Config {
public static function get($path = null) {
    if ($path){
        $config = $GLOBALS['config'];
        $path = explode('/', $path);

        $parent = $path[0];
        $child = $path[1];

        if(isset($config[$parent][$child])) {
            $config = $config[$parent][$child]; 
        }

        return $config;
    }

    return false;
}
}

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    相关资源
    最近更新 更多