search
HomeBackend DevelopmentPHP Tutorialphp 数组求交集问题

php 数组函数 交集

看手册看到这几个方法,不是很明白。哪位大神帮忙解释一下

array_intersect(array1, array2) //比较值 取交集
array_intersect_assoc()         // 比较键名和值 取交集
array_intersect_key(array1, array2)  // 比较键名 取交集

下边这两个不是很明白
array_intersect_uassoc(array1,array2,array3...,function) 
array_intersect_ukey(array1,array2,array3...,function)

function 的返回值有什么作用吗?

最好能举个实际中用到的例子解释一下。

回复讨论(解决方案)

function参数表示一个方法就是 array1,array2,array3等数组里面的值或者键值都会去执行这个函数

function  key_compare_func ( $key1 ,  $key2 ){    if ( $key1  ==  $key2 )        return  0 ;    else if ( $key1  >  $key2 )        return  1 ;    else        return - 1 ;} $array1  = array( 'blue'   =>  1 ,  'red'   =>  2 ,  'green'   =>  3 ,  'purple'  =>  4 ); $array2  = array( 'green'  =>  5 ,  'blue'  =>  6 ,  'yellow'  =>  7 ,  'cyan'    =>  8 ); var_dump ( array_intersect_ukey ( $array1 ,  $array2 ,  'key_compare_func' ));

输出结果:
array(2) {
  ["blue"]=>
  int(1)
  ["green"]=>
  int(3)
}
这些例子php手册下面都有实例的

求两个数组的交集问题可以使用array_intersect(),array_inersect_assoc,array_intersect_key来实现,其中array_intersect()函数是求两个数的交集

<?PHP $array = array("red"=>"Red","green"=>"red4","Red15"=>"Red",7=>"Level","Width"=>"Red","azzzz1"=>"art","peak"=>158); $array1 = array("red"=>"Red2","greena"=>"red","Red15"=>"Red",7=>"Level","Width"=>"Red","azzzz"=>"art","peak"=>158); $num = array_intersect($array,$array1); print_r ($num); echo ""; $num = array_intersect_assoc($array,$array1); print_r($num); echo ""; $num = array_intersect_key($array,$array1); print_r ($num); ?>


详细请看 http://web10000.cn/thread-126-1-1.html
希望能帮助到你

以 #1 的代码为例

function  key_compare_func ( $key1 ,  $key2 ) {    if ( $key1  ==  $key2 )        return  0 ;    else if ( $key1  >  $key2 )        return  1 ;    else        return - 1 ;} $array1  = array( 'blue'   =>  1 ,  'red'   =>  2 ,  'green'   =>  3 ,  'purple'  =>  4 );$array2  = array( 'green'  =>  5 ,  'blue'  =>  6 ,  'yellow'  =>  7 ,  'cyan'    =>  8 );print_r( array_intersect_key ( $array1 ,  $array2 ));print_r( array_intersect_ukey ( $array1 ,  $array2 ,  'key_compare_func' ));
Array(    [blue] => 1    [green] => 3)Array(    [blue] => 1    [green] => 3)

可知 array_intersect_key 内部使用了与 key_compare_func 等价的函数
array_intersect_ukey 可以通过回调函数改变默认行为
function  key_compare_func ( $key1 ,  $key2 ) {    if ( strtolower($key1)  ==  strtolower($key2) )        return  0 ;    else if ( $key1 > $key2 )        return  1 ;    else        return - 1 ;} $array1  = array( 'Blue'   =>  1 ,  'red'   =>  2 ,  'green'   =>  3 ,  'purple'  =>  4 );$array2  = array( 'green'  =>  5 ,  'blue'  =>  6 ,  'yellow'  =>  7 ,  'cyan'    =>  8 );print_r( array_intersect_key ( $array1 ,  $array2 ));print_r( array_intersect_ukey ( $array1 ,  $array2 ,  'key_compare_func' ));
Array(    [green] => 3)Array(    [Blue] => 1    [green] => 3
可以看到,比较时已不再区分大小写了

以 #1 的代码为例

function  key_compare_func ( $key1 ,  $key2 ) {    if ( $key1  ==  $key2 )        return  0 ;    else if ( $key1  >  $key2 )        return  1 ;    else        return - 1 ;} $array1  = array( 'blue'   =>  1 ,  'red'   =>  2 ,  'green'   =>  3 ,  'purple'  =>  4 );$array2  = array( 'green'  =>  5 ,  'blue'  =>  6 ,  'yellow'  =>  7 ,  'cyan'    =>  8 );print_r( array_intersect_key ( $array1 ,  $array2 ));print_r( array_intersect_ukey ( $array1 ,  $array2 ,  'key_compare_func' ));
Array(    [blue] => 1    [green] => 3)Array(    [blue] => 1    [green] => 3)

可知 array_intersect_key 内部使用了与 key_compare_func 等价的函数
array_intersect_ukey 可以通过回调函数改变默认行为
function  key_compare_func ( $key1 ,  $key2 ) {    if ( strtolower($key1)  ==  strtolower($key2) )        return  0 ;    else if ( $key1 > $key2 )        return  1 ;    else        return - 1 ;} $array1  = array( 'Blue'   =>  1 ,  'red'   =>  2 ,  'green'   =>  3 ,  'purple'  =>  4 );$array2  = array( 'green'  =>  5 ,  'blue'  =>  6 ,  'yellow'  =>  7 ,  'cyan'    =>  8 );print_r( array_intersect_key ( $array1 ,  $array2 ));print_r( array_intersect_ukey ( $array1 ,  $array2 ,  'key_compare_func' ));
Array(    [green] => 3)Array(    [Blue] => 1    [green] => 3
可以看到,比较时已不再区分大小写了

array_intersect_ukey明白了。
那array_intersect_uassoc函数,手册上说:“注意,与 array_intersect_assoc() 不同的是除了比较键值,还要比较键名”  手册上给的例子,function中只是比较了值。并没有提到键的比较呢。

function  key_compare_func ( $key1 ,  $key2 ) {    if ( strtolower($key1)  ==  strtolower($key2) )        return  0 ;    else if ( $key1 > $key2 )        return  1 ;    else        return - 1 ;} $array1  = array( 'Blue'   =>  1 ,  'red'   =>  2 ,  'green'   =>  3 ,  'purple'  =>  4 );$array2  = array( 'blue'  =>  1 ,  'green'  =>  5 ,  'yellow'  =>  7 ,  'cyan'    =>  8 );print_r( array_intersect_assoc ( $array1 ,  $array2 ));print_r( array_intersect_uassoc ( $array1 ,  $array2 ,  'key_compare_func' ));
Array()Array(    [Blue] => 1)
看出来了吗?

function  key_compare_func ( $key1 ,  $key2 ) {    if ( strtolower($key1)  ==  strtolower($key2) )        return  0 ;    else if ( $key1 > $key2 )        return  1 ;    else        return - 1 ;} $array1  = array( 'Blue'   =>  1 ,  'red'   =>  2 ,  'green'   =>  3 ,  'purple'  =>  4 );$array2  = array( 'blue'  =>  1 ,  'green'  =>  5 ,  'yellow'  =>  7 ,  'cyan'    =>  8 );print_r( array_intersect_assoc ( $array1 ,  $array2 ));print_r( array_intersect_uassoc ( $array1 ,  $array2 ,  'key_compare_func' ));
Array()Array(    [Blue] => 1)
看出来了吗?
怎样区分,function的参数是‘键’还是‘值’?

不需区分
array_intersect_uassoc 就是用回调函数判别键

如果要自己判断值和键,则要用 array_uintersect_uassoc 函数
并传递两个回调函数

不需区分
array_intersect_uassoc 就是用回调函数判别键

如果要自己判断值和键,则要用 array_uintersect_uassoc 函数
并传递两个回调函数

奥 明白了。 谢谢! 

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor