有没有任何一种内置函数可以比较 PHP 中的数组,而不需要进行循环之类的操作?
$a1 = array(1,2,3);
$a2 = array(1,2,3);
if (array_are_same($a1, $a2)) {
// code here
}
顺便说一下,数组值不总是按相同的顺序排列。
有没有任何一种内置函数可以比较 PHP 中的数组,而不需要进行循环之类的操作?
$a1 = array(1,2,3);
$a2 = array(1,2,3);
if (array_are_same($a1, $a2)) {
// code here
}
顺便说一下,数组值不总是按相同的顺序排列。
如果您不关心键,只关心值,那么这是比较值并确保重复计数的最佳方法。
$mag = '{"1":"1","2":"2","3":"3","4":"3"}';
$mag_evo = '1|2|3';
$test1 = array_values(json_decode($mag, true));
$test2 = array_values(explode('|', $mag_evo));
if($test1 == $test2) {
echo 'true';
}
这个语句不会输出 true,因为 $mag 数组中有两个值等于 3。
如果你只关心值和键而不关心重复的话,这个方法是最好的选择。 $mag = '{"1":"1","2":"2","3":"3","4":"3"}'; $mag_evo = '1|2|3';
$test1 = json_decode($mag, true);
$test2 = explode('|', $mag_evo);
// There is no difference in either array.
if(!array_diff($test1, $test2) && !array_diff($test2, $test1)) {
echo 'true';
}
这将返回true,因为所有值都在两个数组中找到了,但正如之前所指出的,它并不关心重复。
验证交集计数与两个源数组相同
$intersections = array_intersect($a1, $a2);
$equality = (count($a1) == count($a2)) && (count($a2) == count($intersections)) ? true : false;
比较两个数组的值:
$a = array(1,2,3);
$b = array(1,3,2);
if (array_diff($a, $b) || array_diff($b, $a)) {
echo 'Not equal';
}else{
echo 'Equal';
}
我只是想贡献一下这个代码:
echo var_export([1 => 2, 0 => 1, 3] == [1, 2, 3], 1);
输出结果为true
。因此,==
运算符不会检查数组元素的顺序,以您期望的方式进行比较。这意味着上述数组的array_values分别为[2, 1, 3]和[1, 2, 3]。但由于它们的键具有相同的值,所以根据==
运算符它们是相等的。
(记住[1, 2, 3]创建了这个数组:[0 => 1, 1 => 2, 2 => 3])
这是一个简单的方法来获取差异:
$array1 = [40,10,30,20,50];
$array2 = [10,30];
$result = array_filter(
$array1,
function($var) use($array2){
if(in_array($var, $array2)){
return $var;
}
}
);
print_r($result); //Array ( [0] => 10 [1] => 30 )
试试这个:
$array1 = array("street" => array("Althan"), "city" => "surat", "state" => "guj", "county" => "india");
$array2 = array("street" => array("Althan"), "city" => "surat", "state" => "guj", "county" => "india");
if (array_compare($array1, $array2))
{
echo "<pre>";
print_r("succsses..!");
echo "</pre>";
exit;
}
else
{
echo "<pre>";
print_r("Faild..!");
echo "</pre>";
exit;
}
function array_compare($op1, $op2)
{
foreach ($op1 as $key => $val)
{
if (is_array($val))
{
if (array_compare($val, $op2[$key]) === FALSE)
return false;
}
else
{
if (!array_key_exists($key, $op2))
{
return false; // uncomparable
}
elseif ($val < $op2[$key])
{
return false;
}
elseif ($val > $op2[$key])
{
return false;
}
}
}
return true; // $op1 == $op2
}
if(count($a1) == count($a2)){
$result= array_intersect($a1, $a2);
if(count($a1) == count($result))
echo 'the same';
else
echo 'a1 different than a2';
} else
echo 'a1 different than a2';
if (count($a) == count($b) && (!count(array_diff($a, $b))) {
// The arrays are the same
}
应该可以解决问题