Heim  >  Artikel  >  Backend-Entwicklung  >  php数组入门教程之求关联数组的差集

php数组入门教程之求关联数组的差集

WBOY
WBOYOriginal
2016-07-25 08:57:541115Durchsuche
本文介绍下,有关php数组中求关联数组差集的方法,主要是php数组函数array_diff_assoc的用法。有需要的朋友参考下。

在php中,求关联数组的差集。

函数array_diff_assoc()与array_diff()基本相同,只是它在比较时还考虑了数组的键。 因此,只在第一个数组中出现而不再其他输入数组中出现的键/值对才会返回到结果数组中。

其形式如下: array array_diff_assoc(array array1,array array2[,arrayN…])

例子,只返回了[yellow] => Banana,因为这个特殊的键/值对出现在$fruit1中,而在$fruit2和$fruit3中都不存在。

<?php
/**
* 求关联数组的差集
* by bbs.it-home.org
*/
$fruit1 = array("red"=>"Apple","yellow"=>"Banana","orange"=>"Orange");  
$fruit2 = array("yellow"=>"Pear","red"=>"Apple","purple"=>"Grape");  
$fruit3 = array("green"=>"Watermelon","orange"=>"Orange","red"=>"Apple");  
$intersection = array_diff_assoc($fruit1, $fruit2, $fruit3);  
print_r($intersection);  
  
// output  
// Array ( [yellow] => Banana )  
?>

说明: 在php中遍历数组时,通常要遍历数组并获得各个键或值(或者同时获得键和值),PHP为此提供了一些函数来满足需求。 许多函数能完成两项任务,不仅能获取当前指针位置的键或值,还能将指针移向下一个适当的位置。



Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn