如果在数组内部某些字符串相似,我如何比较两个数组?
问题描述:
I simply want to compare two strings
$result = array_diff($original, $new);
var_dump $original:
array(4) {
[0]=>
string(4) "8344"
[1]=>
string(4) "7076"
[2]=>
string(7) "6220940"
[3]=>
string(7) "6220940"
}
var_dump $new:
array(4) {
[0]=>
string(4) "8344"
[1]=>
string(4) "7076"
[2]=>
string(14) "6220940mistake"
[3]=>
string(7) "6220940"
}
var_dump $result:
array(0) {
}
But what I actually expect would be var_dump $result:
array(1) {
[2]=>
string(7) "6220940"
}
I found out that this is happening because I have two strings that are similar. So if every string is unique, there is no problem. But I do sometimes have also similar strings inside my array. Can you help me with this problem?
答
<?php
$a = array("8344", "7076", "6220940", "6220940");
$b = array("8344", "7076", "6220940mistake", "6220940");
var_export(array_diff_assoc($a,$b));
prints
array (
2 => '6220940',
)
see array_diff_assoc
答
You have empty result because all of the elements in $orginal
array are present in array you are comparing against ($new
) - value "6220940" is present at index 3.
You should use array_diff_assoc
instead of array_diff
so you will be comparing array elements with their index assignment.