欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php数组区别取值的四个函数学习

程序员文章站 2024-01-31 21:43:40
...
  1. $array1 = array("a" => "green", "red", "blue");
  2. $array2 = array("b" => "green", "yellow", "red");
  3. $result = array_intersect($array1, $array2);
  4. ?>
复制代码

上例将输出: Array ( [a] => green [0] => red )

2.array_intersect_assoc() 在前一个函数的基础上,返回所有数组中键、值均相同的键值对。

例子:

  1. $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
  2. $array2 = array("a" => "green", "yellow", "red");
  3. $result_array = array_intersect_assoc($array1, $array2);
  4. ?>
复制代码

上例将输出: Array ( [a] => green )

3.array_diff() 携带多个数组,返回第一个数组中有的而后面的数组中没有的所有的值组成的新数组,对应键取自第一个数组。

例子:

  1. $array1 = array("a" => "green", "red", "blue", "red");

  2. $array2 = array("b" => "green", "yellow", "red");
  3. $result = array_diff($array1, $array2);
  4. print_r($result);

  5. ?>
复制代码

上例将输出: Array ( [1] => blue )

4.array_diff_assoc() 在前一个函数的基础上,不仅需要匹配值还要匹配键。

例子:

  1. $array1 = array ("a" => "green", "b" => "brown", "c" => "blue", "red");
  2. $array2 = array ("a" => "green", "yellow", "red");
  3. $result = array_diff_assoc($array1, $array2);
  4. ?>
复制代码

上例将输出: Array ( => brown [c] => blue [0] => red )