php7上的阵列过滤器

php7上的阵列过滤器,php,php-7,php-5.6,Php,Php 7,Php 5.6,我正在使用数组过滤器函数来过滤我的数组并删除DateTime类型的所有对象。我的代码在php5.6上运行得很好,但在php7中我得到了不同的结果。我不确定php7中的更改原因或内容,以及修复它的最佳方法 下面是代码示例 $array1 = ['one', 'two', 'three', new DateTime(), [new DateTime(), new DateTime(), new DateTime()]]; $array2 = ['one', 'two', 'three', ['fo

我正在使用数组过滤器函数来过滤我的数组并删除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\u 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);

由于此函数将修改其输入数组,因此,如果仍需要原始形式的数组,则在使用此函数之前,应先复制一份数组。

在这种情况下,使用递归函数删除
DateTime
对象,而不是
array\u 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);
由于此函数将修改其输入数组,因此如果仍需要原始形式的数组,则在对其使用此函数之前,应先复制该数组