php数组中有一些函数与数学相关的函数,大多都是以array开头然后下划线接一个数学上的英文单词,如下:
1 array_diff() 2 array_diff_assoc() 3 array_intersect() 4 array_intersect_assoc() 5 array_sum() 6 array_product() 7 array_count_values()
首先是数组集合函数,差集array_diff,用于得到目标数组和其他数组的都不同的那些元素
1 $arr = [1, 2, 3, 4, 5, 6, 7, 8]; 2 $arr1 = [1, 2, 3, 4, 6]; 3 $arr2 = [1, 2, 3, 4, 7]; 4 print_r( array_diff( $arr, $arr1, $arr2 ) );
// Array // ( // [4] => 5 // [7] => 8 // )
对于关联数组,和上面的结果一致,因为array_diff函数只比教值是否相同
1 $arr = [ 2 ‘A‘ => 1, ‘B‘ => 2, 3 ‘c1‘ => 3, ‘d1‘ => 4, ‘e1‘ => 5, 4 ‘f‘ => 6, ‘g‘ => 7, ‘h‘ => 8 5 ]; 6 $arr1 = [ 7 ‘a‘ => 1, ‘b‘ => 2, 8 ‘c‘ => 3, ‘d‘ => 4, ‘e‘ => 6 9 ]; 10 $arr2 = [ 11 ‘a‘ => 1, ‘b‘ => 2, 12 ‘c‘ => 3, ‘d‘ => 4, ‘e‘ => 7 13 ]; 14 print_r( array_diff( $arr, $arr1, $arr2 ) ); 15 // Array 16 // ( 17 // [e1] => 5 18 // [h] => 8 19 // )
array_diff_assoc函数从名字上来看,就知道需要比较每个元素的键,区分大小写,
1 $arr = [ 2 ‘A‘ => 1, ‘B‘ => 2, 3 ‘c1‘ => 3, ‘d1‘ => 4, ‘e1‘ => 5, 4 ‘f‘ => 6, ‘g‘ => 7, ‘h‘ => 8 5 ]; 6 $arr1 = [ 7 ‘a‘ => 1, ‘b‘ => 2, 8 ‘c‘ => 3, ‘d‘ => 4, ‘e‘ => 6 9 ]; 10 $arr2 = [ 11 ‘a‘ => 1, ‘b‘ => 2, 12 ‘c‘ => 3, ‘d‘ => 4, ‘e‘ => 7 13 ]; 14 print_r( array_diff_assoc( $arr, $arr1, $arr2 ) ); 15 // Array 16 // ( 17 // [A] => 1 18 // [B] => 2 19 // [c1] => 3 20 // [d1] => 4 21 // [e1] => 5 22 // [f] => 6 23 // [g] => 7 24 // [h] => 8 25 // )
array_intersect()函数,获得目标函数与其他函数都相同的函数,只比教值
1 $arr = [ 2 ‘A‘ => 1, ‘B‘ => 2, 3 ‘c1‘ => 3, ‘d1‘ => 4, ‘e1‘ => 5, 4 ‘f‘ => 6, ‘g‘ => 7, ‘h‘ => 8 5 ]; 6 $arr1 = [ 7 ‘a‘ => 1, ‘b‘ => 2, 8 ‘c‘ => 3, ‘d‘ => 4, ‘e‘ => 6 9 ]; 10 $arr2 = [ 11 ‘a‘ => 1, ‘b‘ => 2, 12 ‘c‘ => 3, ‘d‘ => 4, ‘e‘ => 7 13 ]; 14 print_r( array_intersect( $arr, $arr1, $arr2 ) ); 15 // Array 16 // ( 17 // [A] => 1 18 // [B] => 2 19 // [c1] => 3 20 // [d1] => 4 21 // )
array_intersect_assoc()只有键和值都一样才行。
1 $arr = [ 2 ‘a‘ => 1, ‘b‘ => 2, 3 ‘c1‘ => 3, ‘d1‘ => 4, ‘e1‘ => 5, 4 ‘f‘ => 6, ‘e‘ => 7, ‘h‘ => 8 5 ]; 6 $arr1 = [ 7 ‘a‘ => 1, ‘b‘ => 2, 8 ‘c‘ => 3, ‘d‘ => 4, ‘e‘ => 6 9 ]; 10 $arr2 = [ 11 ‘a‘ => 1, ‘b‘ => 2, 12 ‘c‘ => 3, ‘d‘ => 4, ‘e‘ => 7 13 ]; 14 print_r( array_intersect_assoc( $arr, $arr1, $arr2 ) ); 15 // Array 16 // ( 17 // [a] => 1 18 // [b] => 2 19 // )
array_sum()函数计算数组中所有元素值的和,array_product()函数计算数组中所有元素的积,
对于元素值为数字,很符合数学,但如果是字符和数字混杂。
1 $arr = [1, 2, 3, 4, 5, ‘a‘, ‘asss‘]; 2 $arr1 = [ ‘1‘, ‘2‘, ‘2as‘, ‘2a2‘ ]; 3 echo array_sum($arr), PHP_EOL, array_sum($arr1);
15 7
这就采用了自动类型转换(字符串转数字)的规则了。对于array_product()这个函数,数学规则的不同,导致结果也是不同。
1 $arr = [1, 2, 3, 4, 5, ‘a‘, ‘asss‘]; 2 $arr1 = [ ‘1‘, ‘2‘, ‘2as‘, ‘2a2‘ ]; 3 echo array_product($arr), PHP_EOL, array_product($arr1); 4 // 0 5 // 8
array_count_values()函数,统计每一个值的个数
1 $arr = [1, 2, 3, ‘1‘, ‘2‘, 1, 2]; 2 print_r( array_count_values($arr) ); 3 // Array 4 // ( 5 // [1] => 3 6 // [2] => 3 7 // [3] => 1 8 // )
从结果来看似乎也涉及到了自动类型转换规则。注意:向这个函数中传入二维以上数组,会有warning提示,也不会统计二维数组中一维数组的值。
原文地址:https://www.cnblogs.com/zxcv123/p/11809074.html
时间: 2024-10-29 16:00:26