欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

php 得到数组的交集 示例 AG chatgpt 有大用 有大大用

PHP 获取数组的交集示例

在PHP中,可以使用 array_intersect 系列函数来获取数组的交集(两个或多个数组中共同存在的元素)。

基本示例:array_intersect

php
<?php $array1 = ["a", "b", "c", "d"]; $array2 = ["b", "c", "e", "f"]; // 获取两个数组的交集 $intersection = array_intersect($array1, $array2); print_r($intersection); /* 输出: Array (    [1] => b    [2] => c ) */ ?>

多个数组的交集

php
<?php $array1 = ["apple", "banana", "orange"]; $array2 = ["banana", "kiwi", "pear"]; $array3 = ["banana", "peach", "grape"]; // 获取多个数组的交集 $intersection = array_intersect($array1, $array2, $array3); print_r($intersection); /* 输出: Array (    [1] => banana ) */ ?>

关联数组的交集

php
<?php $array1 = ["name" => "John", "age" => 25, "city" => "New York"]; $array2 = ["name" => "John", "age" => 30, "country" => "USA"]; // 比较键的交集(array_intersect_key) $keysIntersection = array_intersect_key($array1, $array2); print_r($keysIntersection); /* 输出: Array (    [name] => John    [age] => 25 ) */ // 比较值的交集(array_intersect) $valuesIntersection = array_intersect($array1, $array2); print_r($valuesIntersection); /* 输出: Array (    [name] => John ) */ // 比较键和值的交集(array_intersect_assoc) $assocIntersection = array_intersect_assoc($array1, $array2); print_r($assocIntersection); /* 输出: Array (    [name] => John ) */ ?>

自定义比较函数的交集

php
<?php function compareIgnoreCase($a, $b) {    return strtolower($a) <=> strtolower($b); } $array1 = ["Apple", "Banana", "Orange"]; $array2 = ["apple", "banana", "PEAR"]; // 使用自定义比较函数获取交集 $intersection = array_uintersect($array1, $array2, 'compareIgnoreCase'); print_r($intersection); /* 输出: Array (    [0] => Apple    [1] => Banana ) */ ?>

注意事项

  1. array_intersect - 比较值的交集,保留第一个数组的键

  2. array_intersect_key - 比较键的交集

  3. array_intersect_assoc - 同时比较键和值的交集

  4. array_uintersect - 使用自定义函数比较值的交集

  5. 这些函数都区分大小写,除非使用自定义比较函数

选择哪种方法取决于你需要比较的是值、键还是两者都需要比较。


普通分类: