📜  php array_intersect_assoc - PHP (1)

📅  最后修改于: 2023-12-03 14:45:10.378000             🧑  作者: Mango

PHP函数介绍:array_intersect_assoc()

一、概述

array_intersect_assoc() 是 PHP 中的一种数组函数,用于返回两个或多个数组中相同键值对的交集。

array_intersect() 不同的是,它会比较键和值是否都相等。

二、语法
array_intersect_assoc(array1, array2, ...)
三、参数

函数共有多个参数(数组),可以根据需要传递。

  • array1:必需。第一个数组。
  • array2:可选。第二个数组。
  • ...:可选。第三个及以后的数组。
四、返回值

函数会返回由两个或多个数组中键值对都存在的元素组成的新数组。如果有相同的键值对在多个数组中出现,则只有在第一个数组中出现的元素才会被返回。

五、示例
1. 基本使用
<?php
$a1 = array("a" => "red", "b" => "green", "c" => "blue");
$a2 = array("a" => "red", "b" => "blue", "d" => "yellow");

$result = array_intersect_assoc($a1, $a2);

print_r($result);
?>

输出:

Array
(
    [a] => red
)
2. 多个数组求交集
<?php
$a1 = array("a" => "red", "b" => "green", "c" => "blue");
$a2 = array("a" => "red", "b" => "blue", "d" => "yellow");
$a3 = array("a" => "red", "b" => "pink", "e" => "white");

$result = array_intersect_assoc($a1, $a2, $a3);

print_r($result);
?>

输出:

Array
(
    [a] => red
)
3. 数组键值不相等
<?php
$a1 = array("a" => "red", "b" => "green", "c" => "blue");
$a2 = array("a" => "red", "b" => "blue", "c" => "yellow");

$result = array_intersect_assoc($a1, $a2);

print_r($result);
?>

输出:

Array
(
)
六、总结

array_intersect_assoc() 是一个非常有用的 PHP 函数,它可以帮助我们快速地求出多个数组中相同的键值对。在实际开发中,可以应用于很多场景,如:多维数组去重、数据分析等等。