array_diff() 会从结果中删除元素,即使值匹配但键不同

问题描述 投票:0回答:2

这是一个非常简单的问题,但 PHP 文档没有解释为什么会发生。

我有这个代码:

var_dump($newattributes);
var_dump($oldattributes);
var_dump(array_diff($newattributes, $oldattributes));

为了简单起见,我将省略我实际使用的结构的大部分(因为每个结构都有 117 个元素长)并切入案例。

我有一个名为

$newattributes
的数组,看起来像:

array(117){
    // Lots of other attributes here
    ["deleted"] => int(1)
}

另一个叫

$oldattributes
,看起来像:

array(117){
    // Lots of other attributes here
    ["deleted"] => string(1) "0"
}

哪个看起来不一样?根据

array_diff
:没有。我从
array_diff
得到的输出是:

array(0) { } 

我已阅读文档页面,但它说:

两个元素被认为相等当且仅当 (string) $elem1 === (字符串)$elem2。换句话说:当字符串表示相同时。

我不确定“1”如何反对等于“0”。

我是否看到了一些我没有考虑到的

array_diff()
警告?

php arrays filter associative-array array-difference
2个回答
11
投票

问题可能在于您正在使用关联数组:您应该尝试对关联数组使用以下内容:array_diff_assoc()

<?php 
    $newattributes = array(
       "deleted" => 1 
    );

    $oldattributes = array(
       "deleted" => "0" 
    );

    $result = array_diff_assoc($newattributes, $oldattributes);

    var_dump($result);
?>

结果:

   array(1) {
       ["deleted"]=>
       int(1)
   }

2
投票

确实也发生在我身上(当有多个值时)

$new = array('test' => true, 'bla' => 'test' 'deleted' => 1);
$old = array('test' => true, 'deleted' => '0');

对于 full array_diff 你需要做一些额外的工作,因为默认情况下它返回一个 相对补集

试试这个:

array_diff(array_merge($new, $old), array_intersect($new, $old))

结果:

Array
(
    [bla] => test
    [deleted] => 0
)
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.