使用带分隔符的字符串,如何获得相对于已解析字符串的数组项?


Using a delimited string, how do I get an array item relative to the parsed string?

给定格式为"one/two"或"one/two/three"的字符串,使用/作为分隔符,我需要在2d数组中获取值(作为引用)。在本例中,我访问的是$_SESSION变量。

SessionAccessor::getData($str)函数中,我不知道该把什么放在那里使它解析分隔的字符串并返回数组项。我不知道我访问的是哪个数组键。该函数将是泛型的。

class SessionAccessor {
    static &function getData($str) {
         // $str = 'one/two/three'
         return $_SESSION['one']['two']['three'];
    }
}
/** Below is an example of how it will be expected to work **/
/**********************************************************/
// Get a reference to the array
$value =& SessionAccessor::getData('one/two/three');
// Set the value of $_SESSION['one']['two']['three'] to NULL
$value = NULL;

这是@RocketHazmat在StackOverflow提供的解决方案:

class SessionAccessor {
    static function &getVar($str) {
        $arr =& $_SESSION;
        foreach(explode('/',$str) as $path){
            $arr =& $arr[$path];
        }
        return $arr;
    }
}

从你的描述来看,听起来这就是你想要的;

&function getData($str) {
    $path = explode('/', $str);
    $value = $_SESSION;
    foreach ($path as $key) {
        if (!isset($value[$key])) {
            return null;
        }
        $value = $value[$key];
    }
    return $value;
}

编辑

为了允许设置这些值,最好使用setData方法。这应该能达到你的期望;

class SessionAccessor {
    static function getData($str) {
        $path = explode('/', $str);
        $value = $_SESSION;
        foreach ($path as $key) {
            if (!isset($value[$key])) {
                return null;
            }
            $value = $value[$key];
        }
        return $value;
    }
    static function setData($str, $newValue) {
        $path = explode('/', $str);
        $last = array_pop($path);
        $value = &$_SESSION;
        foreach ($path as $key) {
            if (!isset($value[$key])) {
                $value[$key] = array();
            }
            $value = &$value[$key];
        }
        $value[$last] = $newValue;
    }
}