php7上的数组过滤器


array filter on php7

我正在研究数组过滤函数来过滤我的数组并删除类型DateTime的所有对象我的代码在php5.6上工作得很好,但在php7中我得到了不同的结果,我不知道为什么或在php7中发生了什么变化以及修复它的最佳方法

这里的代码示例

$array1 = ['one', 'two', 'three', new DateTime(), [new DateTime(), new DateTime(), new DateTime()]];
$array2 = ['one', 'two', 'three', ['four', 'five', 'six']];
$data = array_filter($array1, $callback = function (&$value) use (&$callback) {
    if (is_array($value)) {
        $value = array_filter($value, $callback);
    }
    return ! $value instanceof DateTime;
});

如果我在php5.6中运行这段代码,我得到

array(4) { [0]=> string(3) "one" [1]=> string(3) "two" [2]=> string(5) "three" [4]=> array(0) { } }

它的工作很好,通过删除所有对象类型的DateTime,但如果我在php7中运行代码,我得到

array(4) { [0]=> string(3) "one" [1]=> string(3) "two" [2]=> string(5) "three" [4]=> array(3) { [0]=> object(DateTime)#2 (3) { ["date"]=> string(26) "2016-06-27 18:53:11.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(11) "Asia/Riyadh" } [1]=> object(DateTime)#3 (3) { ["date"]=> string(26) "2016-06-27 18:53:11.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(11) "Asia/Riyadh" } [2]=> object(DateTime)#4 (3) { ["date"]=> string(26) "2016-06-27 18:53:11.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(11) "Asia/Riyadh" } } }

正如你所看到的,它只从第一级数组中删除DateTime类型的对象,忽略第二级数组而不过滤它们,你能帮助我了解php7中发生了什么变化导致这种行为以及修复它的最佳方法

在这种情况下,使用递归函数删除DateTime而不是array_filter可能会更简单。

$array1 = ['one', 'two', 'three', new DateTime(), 
              [new DateTime(), new DateTime(), new DateTime()]];
function removeDateTimes(&$x) {
    foreach ($x as $k => &$v) {
        if ($v instanceof DateTime) unset($x[$k]);
        elseif (is_array($v)) removeDateTimes($v);
    }
}
removeDateTimes($array1);

因为这个函数会修改它的输入数组,如果你仍然需要它的原始形式,在对它使用这个函数之前,你应该复制一个数组。