【发布时间】:2016-07-18 15:29:38
【问题描述】:
我正在使用 httpfoundation https://github.com/symfony/http-foundation
我正在用这个替换所有$_SESSIONs。
即
$_SESSION['user'] = 'foo' 变为 $this->Session->set('user', 'foo');
使用会话类。
我在使用多维数组时遇到问题。
我可以通过这样做得到数据:
$this->Session->get('user')['group']['id']
但是,当我想将深度数组设置/删除为某个值时,我没有办法这样做吗?
$this->Session->set(array('user' => array('group' => 'id')), 200); // Errors
$this->Session->remove(array('form_data' => 'test')); // Errors
肯定有一种干净的方法可以做到这一点吗?我认为甚至不可能使用这个 httpfoundation 会话术语来设置深度数组值。
这些似乎是我可以使用的唯一方法:
all()
keys()
replace()
add()
get()
set()
has()
remove()
如果我不够清楚,请大声喊叫,干杯
遵循马特回答的新方法。
设置测试值
$Session->set( 'test', array('test1' => array('test2' => array('test3' => 'test4') )) );
运行方法
$Session->setDeep('test', array('test1', 'test2', 'test3'), 'flip');
$Session->removeDeep('test', array('test1', 'test2', 'test3'));
方法有:
/**
* Removes a deep variable item
* @param string $key Top-most array key value
* @param array $path one-dimentional array of path: array('user', 'group', 'id')
*/
public function removeDeep($key, $path)
{
$new_arr = $this->get($key);
$depth = count($path);
switch ($depth) {
case 1:
return false;
break;
case 2:
unset( $new_arr[$path[0]][$path[1]] );
break;
case 3:
unset( $new_arr[$path[0]][$path[1]][$path[2]] );
break;
case 4:
unset( $new_arr[$path[0]][$path[1]][$path[2]][$path[3]] );
break;
}
$this->set($key, $new_arr);
}
/**
* Sets a deep variable item
* @param string $key Top-most array key value
* @param array $path one-dimentional array of path: array('user', 'group', 'id')
* @param mixed $value The value you will set the path to
*/
public function setDeep($key, $path, $value)
{
$new_arr = $this->get($key);
$depth = count($path);
switch ($depth) {
case 1:
return false;
break;
case 2:
$new_arr[$path[0]][$path[1]] = $value;
break;
case 3:
$new_arr[$path[0]][$path[1]][$path[2]] = $value;
break;
case 4:
$new_arr[$path[0]][$path[1]][$path[2]][$path[3]] = $value;
break;
}
$this->set($key, $new_arr);
}
【问题讨论】: