在我的Web应用程序中,我有一些数组,该数组返回的数组类似于以下输出:
[
0=>
pk = "ID"
username = "PAGE"
full_name = "PAGE"
is_private = false
reel_auto_archive = "on"
latest_reel_media = "1536080134"
is_favorite = false
1=>
pk = "ID"
username = "PAGE"
full_name = "PAGE"
is_private = false
reel_auto_archive = "on"
latest_reel_media = "1536050134"
is_favorite = false
]
因为我想使用array_filter来过滤latest_reel_media
的数组,当它比例如1535707694
低时是时间戳记
例如:
$mediaTime = 86400 * 3;
$time_limit = strtotime(date("Y-m-d H:i:s")) - $mediaTime;
$followers = array_filter($followers, [new LowerThanFilter($time_limit,'latest_reel_media'), "isLower"]);
LowerThanFilter
类:
class LowerThanFilter
{
private $limit;
private $latest_reel_media;
function __construct($limit,$latest_reel_media)
{
$this->limit = $limit;
$this->latest_reel_media=$latest_reel_media;
}
function isLower($i)
{
return $i <= $this->limit;
}
}
在测试了超过100000条记录的代码后,array_fillter
不起作用并返回了所有不正确的100000
条记录
答案 0 :(得分:1)
您必须与latest_reel_media
键进行比较。因此,在使用您的类时,应将其设置为属性(以便您的类可重用)。
class LowerThanFilter
{
private $limit;
// $key is an optional parameter
function __construct($limit, ?string $key = null)
{
$this->limit = $limit;
$this->key = $key;
}
// Thanks @weirdan for the use of __invoke()
function __invoke($i)
{
// if $key is set, compare with key
if (!is_null($this->key)) {
return $i->{$this->key} <= $this->limit;
}
return $i <= $this->limit;
}
}
然后像这样过滤:
$followers = array_filter($followers, new LowerThanFilter($time_limit, 'latest_reel_media'));
另一种解决方案是使用具有继承(use ($var)
)的anonymous function(不可重用,但值得一看):
// this can easily stand on a single line too
$followers = array_filter($followers, function($i) use ($time_limit) {
return $i['latest_reel_media'] <= $time_limit;
});
答案 1 :(得分:0)
仅将isLower函数中的return语句替换为此,它将正常工作:
返回$ i ['latest_reel_media'] <= $ this-> limit;