根据
Joomla JSession documentation
这个
JSession
类确实提供了
getIterator
方法返回
ArrayIterator
.
作为一种可重用的方法,您可以实现自己的
FilterIterator
类,仅迭代具有特定前缀的项,并且
任选地
从键中除去前缀。
在代码中,迭代器
$sessionArrayIter = $session->getIterator();
因为我不太了解Joomla,也不运行任何安装程序,所以我将欺骗该部分:
$sessionArray = ['aa_test1' => 1, 'bb_test2' => 2, 'aa_test3' => 3, 'cc_test4' => 4];
$sessionArrayIter = new ArrayIterator($sessionArray);
类实现
然后我们执行
PrefixFilterIterator
类扩展PHP的抽象
滤波器迭代器
班级。
class PrefixFilterIterator extends FilterIterator
{
private
$_prefix,
$_prefixLength,
$_strip_prefix
;
public function __construct(Iterator $iterator, string $prefix, bool $strip_prefix = false)
{
parent::__construct($iterator);
$this->set_prefix($prefix, $strip_prefix);
}
public function set_prefix(string $prefix, ?bool $strip_prefix = null) : void
{
$this->_prefix = $prefix;
$this->_prefixLength = strlen($prefix);
if(null !== $strip_prefix)
$this->_strip_prefix = $strip_prefix;
}
// conditionally remove prefix from key
public function key() /* : mixed scalar */
{
return $this->_strip_prefix ? substr(parent::key(), $this->_prefixLength) : parent::key();
}
// accept prefixed items only
public function accept() : bool
{
return 0 === strpos(parent::key(), $this->_prefix);
}
}
用法
为了迭代筛选的项,我们创建了一个新的迭代器实例。
$prefixIter = new PrefixFilterIterator($sessionArrayIter, 'aa_', true);
foreach ($prefixIter as $k => $v)
echo "$k => $v", PHP_EOL;
产量
test1 => 1
test3 => 3
备注、限制、待办事项:
上面的代码运行在
php & gt=7.1
要支持php 7.0,必须修改类型提示。
:void
在php<7.1中不受支持,必须删除,同样
?bool
必须更改为
bool
.
这是一个简单的实现,关注问题中的问题,以减少答案中的“噪音”。
mbstring
是php的非默认扩展。因此,我没有使用多字节字符串函数。但是,数组键可以包括多字节字符集。为了支持这些键,需要一些字符串函数包装器的条件实现,如果安装了相应的函数,就需要使用它们。这个
preg_*
函数
u
修饰符可以是支持多字节Unicode键的替代项。