array_diff 并不总是正确的

array_diff not always correct

我展示了数组中值之间差异的示例,有时无法正常工作。

$fields = array(
    '1x1' => 'k',
    '1x2' => 'B',
    '1x3' => 'c',
    '2x1' => 'd',
    '2x2' => 'x',
    '2x3' => 'Y',
    '3x1' => 'b',
    '3x2' => 'e',
    '3x3' => 'f'
);

print_r($fields);

$answer = array(
    'a',
    'b',
    'c',
    'd',
    'x',
    'y',
    'z',
    'e',
    'f'
);

print_r($answer);

echo '<hr />DIFF:<br />';

print_r(array_diff($fields, $answer));

?>

结果是:

(
    [1x1] => k
    [1x2] => B
    [2x3] => Y
)

但应该是:

(
    [1x1] => k
    [1x2] => B
    [2x3] => Y
    [3x1] => b
)

为什么 PHP b 等于 z? 如何修复?

看到您将 'b' 放入 $answer 和 $fields 数组中。

所以这就是为什么它给你这样的输出。

这是正确的。根据array_diff() documentation:

array array_diff ( array $array1 , array $array2 [, array $... ] )

Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.

文档中的另一个重要信息:

Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.

所以在 $answers 数组中没有 $fields 数组的 k, B, Y 个元素。

方法没有错,比较2个列表,都包含b