企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ## **数组合并** ### PHP 数组相加 和 数组合并array_merge ``` $arr1 = array("a"=>"PHP","b"=>"java","python"); $arr2 = array("c" =>"ruby","d" => "c++","go","a"=> "swift"); $arr3 = array_merge($arr1,$arr2); $arr4 = $arr1 + $arr2; var_dump($arr3); var_dump($arr4); ``` 输出: ``` array ( 'a' => 'swift', 'b' => 'java', 0 => 'python', 'c' => 'ruby', 'd' => 'c++', 1 => 'go', ) array ( 'a' => 'PHP', 'b' => 'java', 0 => 'python', 'c' => 'ruby', 'd' => 'c++', ) ``` 区别: 当下标为数值时,array\_merge()不会覆盖掉原来的值,但arrayA+arrayB合并数组则会把最先值arrayA的值作为最终结果返回,而把arrayB数组拥有相同键名的那些值“抛弃”掉,而不是覆盖 当下标为字符时,arrayA+arrayB 仍然把最先出现的值作为最终结果返回,而把后面的数组拥有相同键名的那些值“抛弃”掉,但array\_merge()此时会覆盖掉前面相同键名的值 ### [array\_​combine ($keysArr , $valuesArr);](https://www.php.net/manual/zh/function.array-combine.php "array_​combine")  两个数组分别作为新数组的键与值进行合并 ## **数组排序** ### **排序函数一览** | 函数名称 | 排序依据 | 数组索引键保持 | 排序的顺序 | 相关函数 | | --- | --- | --- | --- | --- | | [array\_multisort()](https://www.php.net/manual/zh/function.array-multisort.php) | 值 | 键值关联的保持,数字类型的不保持 | 第一个数组或者由选项指定 | [array\_walk()](https://www.php.net/manual/zh/function.array-walk.php) | | [asort()](https://www.php.net/manual/zh/function.asort.php) | 值 | 是 | 由低到高 | [arsort()](https://www.php.net/manual/zh/function.arsort.php) | | [arsort()](https://www.php.net/manual/zh/function.arsort.php) | 值 | 是 | 由高到低 | [asort()](https://www.php.net/manual/zh/function.asort.php) | | [krsort()](https://www.php.net/manual/zh/function.krsort.php) | 键 | 是 | 由高到低 | [ksort()](https://www.php.net/manual/zh/function.ksort.php) | | [ksort()](https://www.php.net/manual/zh/function.ksort.php) | 键 | 是 | 由低到高 | [asort()](https://www.php.net/manual/zh/function.asort.php) | | [natcasesort()](https://www.php.net/manual/zh/function.natcasesort.php) | 值 | 是 | 自然排序,大小写不敏感 | [natsort()](https://www.php.net/manual/zh/function.natsort.php) | | [natsort()](https://www.php.net/manual/zh/function.natsort.php) | 值 | 是 | 自然排序 | [natcasesort()](https://www.php.net/manual/zh/function.natcasesort.php) | | [rsort()](https://www.php.net/manual/zh/function.rsort.php) | 值 | 否 | 由高到低 | [sort()](https://www.php.net/manual/zh/function.sort.php) | | [shuffle()](https://www.php.net/manual/zh/function.shuffle.php) | 值 | 否 | 随机 | [array\_rand()](https://www.php.net/manual/zh/function.array-rand.php) | | [sort()](https://www.php.net/manual/zh/function.sort.php) | 值 | 否 | 由低到高 | [rsort()](https://www.php.net/manual/zh/function.rsort.php) | | [uasort()](https://www.php.net/manual/zh/function.uasort.php) | 值 | 是 | 由用户定义 | [uksort()](https://www.php.net/manual/zh/function.uksort.php) | | [uksort()](https://www.php.net/manual/zh/function.uksort.php) | 键 | 是 | 由用户定义 | [uasort()](https://www.php.net/manual/zh/function.uasort.php) | | [usort()](https://www.php.net/manual/zh/function.usort.php) | 值 | 否 | 由用户定义 | [uasort()](https://www.php.net/manual/zh/function.uasort.php) | ### [**array\_​multisort**](https://www.php.net/manual/zh/function.array-multisort.php "array_​multisort") ( &$array1, mixed SORT_ASC, mixed SORT_REGULAR,&$array2, mixed SORT_ASC, mixed SORT_REGULAR, mixed $... = ? ): bool对多个数组或多维数组进行排序 参数1:要排序的array 参数2:之前array参数要排列的顺序。**`SORT_ASC`**按照上升顺序排序,**`SORT_DESC`** 按照下降顺序排序 参数3:为array参数设定选项: 排序类型标志: * **`SORT_REGULAR`**\- 将项目按照通常方法比较(不修改类型) * **`SORT_NUMERIC`**\- 按照数字大小比较 * **`SORT_STRING`**\- 按照字符串比较 * **`SORT_LOCALE_STRING`**\- 根据当前的本地化设置,按照字符串比较。 它会使用 locale 信息,可以通过[setlocale()](https://www.php.net/manual/zh/function.setlocale.php)修改此信息。 * **`SORT_NATURAL`**\- 以字符串的"自然排序",类似[natsort()](https://www.php.net/manual/zh/function.natsort.php) * **`SORT_FLAG_CASE`**\- 可以组合 (按位或 OR)**`SORT_STRING`**或者**`SORT_NATURAL`** 大小写不敏感的方式排序字符串。 * ...更多参数:可选的选项,可提供更多数组,跟随在 sort order 和 sort flag 之后。 提供的数组和之前的数组要有相同数量的元素。 换言之,排序是按字典顺序排列的。 通常可以用此函数进行排名 ``` $arr=[286,298,284,288]; array_multisort($arr,SORT_DESC,SORT_REGULAR); array_multisort($arr,SORT_REGULAR,SORT_DESC);//数组之后跟的两个参数可以呼互换 //[298,288,268,284] ``` 示例 #2 排序多维数组 ``` $ar = array( array("10", 11, 100, 100, "a"), array( 1, 2, "2", 3, 1) ); array_multisort($ar[0], SORT_ASC, SORT_STRING, $ar[1], SORT_NUMERIC, SORT_DESC); var_dump($ar); ``` #### 对数据库指定的列排序,这里指定cost_staus和subject两个进行排序(太神奇了) ``` $newdata =[ ['id' => 1,'cost_staus'="1",'subject'=>"营销部"], ['id' => 2,'cost_staus'="1",'subject'=>"招待部"], ['id' => 3,'cost_staus'="0",'subject'=>"营业部"] ] foreach ($newdata as $key => $row) { $cost_staus[$key] = $row['cost_staus']; $subject[$key] = $row['subject']; } //对这两个进行升序,优先级以靠前的参数为主,其他字段传入newdata按照普通排序 array_multisort($cost_staus, SORT_ASC, $subject, SORT_ASC, $newdata); ``` **示例 4: 不区分大小写字母排序** **`SORT_STRING`**和**`SORT_REGULAR`**都是区分大小写字母的,大写字母会排在小写字母之前。 要进行不区分大小写的排序,就要按照原数组的小写字母拷贝来排序。 ``` $array = array('Alpha', 'atomic', 'Beta', 'bank'); $array_lowercase = array_map('strtolower', $array); array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $array); print_r($array); ``` 输出 ~~~ Array ( [0] => Alpha [1] => atomic [2] => bank [3] => Beta ) ~~~ ## **分割字符串为数组** ### explode ~~~ $str = "Hello world. I love Shanghai!"; print_r (explode(" ",$str));//Array ( [0] => Hello [1] => world. [2] => I [3] => love [4] => Shanghai! ) var_dump(explode('<=>','a<=>b c<=>d'));//array ( 0 => 'a', 1 => 'b c', 2 => 'd', ) ~~~ ### preg_split 多处分割 ``` $str="FreeSpace=46627741696 Size=85897945088"; $res=preg_split("/[(Size=)|(FreeSpace=)]+/", trim($v),-1, PREG_SPLIT_NO_EMPTY);//PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_OFFSET_CAPTURE 结果: array ( 0 => '46627741696 ', 1 => '85897945088', ) ``` **数组:** >[danger]PHP使用explode和preg_split截取出来的数组,获取指定下标时报错:Undefined offset: 1 **解决办法** 首先指定explode截取长度;然后使用array\_pad将未定义的数组长度的值补全,这里赋值为null list($a, $b, $c, $d) = array\_pad(explode("-", $str, 4), 4, null); 方法2:添加错误抑制符@ >[danger]**注意:[array\_​walk\_​recursive](https://www.php.net/manual/zh/function.array-walk-recursive.php "array_​walk_​recursive")、 [array\_​merge\_​recursive](https://www.php.net/manual/zh/function.array-merge-recursive.php "array_​merge_​recursive") 、[array\_​replace\_​recursive](https://www.php.net/manual/zh/function.array-replace-recursive.php "array_​replace_​recursive") 支持多维数组,其他都是一维数组的操作?** ## **删除及过滤** ### **array\_filter**($arr ,$callback \[, int $flag = 0 \]\] );//数组过滤删除回调函数中返回fasle的数组 ~~~ $arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4]; //ARRAY_FILTER_USE_KEY 只接受键 array_filter($arr, function($key) { return $key == 'b'; #当为true时则保留 }, ARRAY_FILTER_USE_KEY); #['b'=>2] //ARRAY_FILTER_USE_BOTH 接受键值 array_filter($arr, function($v, $key) { return $key == 'b' || $v == 4; }, ARRAY_FILTER_USE_BOTH); #['b'=>2,'d'=>4]; //只有一个参数时会将数组的值转为boolean 为true 则保留,否则删除 ~~~ ### 使用回调函数过滤数组的元素 ~~~ $arr = array('foo', 5, 10, 'bar',false);//第一个参数数组的值作为填充数组的键,第二个参数作为值 $a=array_filter($arr ,function($value,$key){//如果没有回调函数将删除 array 中所有等值为 FALSE 的条目 if($key==1){ return false;//此函数内一定要有返回true,保留数组中返回true的元素 }else{ return true; } //return ==1; },ARRAY_FILTER_USE_BOTH);//数组过滤删除回调函数中返回fasle的数组值 存在ARRAY_FILTER_USE_BOTH时,回调函数同时接受键值两个参数否则只接受key /* 返回 array{ [0]=> "foo", [2]=>10, [3]=>"bar", [4]=>false, } */ $a=array_filter($arr); /* 返回 array{ [0]=> "foo", [1]=>5, [2]=>10, [3]=>"bar", } */ ~~~ 获取数组指定范围的新数组 ``` $arr=[1,2,3,4,5,6,7,8,9,10,11,12]; function getArrRangeValue($arr, $min, $max){ $newArr=array_filter($arr ,function($value,$key) use($min,$max){ if ($value>=$min && $value<=$max) { return true; } },ARRAY_FILTER_USE_BOTH); return $newArr; } $res=getArrRangeValue($arr,2,5); print_r($res);//Array([1] => 2,[2] => 3,[3] => 4,[4] => 5) ``` ### **array_splice**($arr,$start_index_int,$remove_length);//移除索引数组中指定位置及之后的length个元素,返回被移除的元素数组` ~~~ $arr=[1,2,3,4,5]; array_splice($arr,0,2);//返回[1,2] 此时$arr=[3,4,5] ~~~ ### **unset**()函数删除的话,数组的索引值没有变化。 ~~~ $arr=[1,2,3,4]; $unset($arr[1]);//arr=[0=>1,2=>3,3=>4] ~~~ ### **array_pop**($arr);删除最后一个元素(出栈)  ~~~ $stack = array("orange", "banana", "apple", "raspberry"); $fruit = array_pop($stack); ~~~ ### **array_shift**( `$arr` );删除第一个元素 ~~~ $arr= array("orange", "banana", "apple", "raspberry"); $fruit = array_shift($arr);//[0=>'banana',1=>'apple',2=>'raspberry']; ~~~ ## **数组元素追加** ### **array_splice**($arr,$start_index_int,$remove_length,$replace_arr);//$start_index_int,$remove_length组合不再$arr的范围即不能删除和替换时就插入 ### $arr[]='value'; ### **array_push**($arr,$value1,$value2,...);//尾部插入新单元(入栈) 就新增单元而言$arr\[\]=value 效率更高  注意:array\_splice不保留键名每次都会截断并重新生成索引键 ### **array\_unshift**($arr,value1,$value2,$valueN...)  数组的开头插入value ## **随机:** ### shuffle  打乱数组 ### array_rand($arr,5)    重数组总共随机抽取5个一维元素 ## **键值互换**: ### **array_flip**($arr) ## **合并** ### [array_​merge](https://www.php.net/manual/zh/function.array-merge.php "array_​merge") ### [array_​merge\_​recursive](https://www.php.net/manual/zh/function.array-merge-recursive.php "array_​merge_​recursive") ## **拆分** ### **array_chunk**($arr,$size,false为不保留键)   按照每个$size个数拆分数组 ### [**array_​chunk**($arr, $size, false);//[1,2,3,4]==>[[1,2],[3,4]]   分割成size大小的数组 第三个参数preserve_keys是否保留原键名](https://www.php.net/manual/zh/function.array-chunk.php "array_​chunk") ## **截取** ### **array_slice**($arr ,$start\_index [,$length = NULL [,$preserve_keys = false ]] );//length 为null 截取 start_index ~数组末尾的 ~~~ $input = array("a", "b", "c", "d", "e"); #第二个参数为父则从数组末尾开始,第三个参数为负则截取在末尾至(-参数)位置之前的 第三参数为true则不重置数字索引 array_slice($input, 2); //[ "c", "d", "e"] array_slice($input, -2, 1); // ["d"] array_slice($input, 0, 3); //["a","b","c"] array_slice($input, 2, -1); //[0=>'c',1=>'d'] array_slice($input, 2, -1, true);//[2=>'c',3=>'d'] ~~~ ## **数组元素替换(修改)** ### **array_splice**($arr,$start_index_int,$remove_length,$replace_arr);//第四个参数存在时不是移除而是修改` ### **array_replace_recursive**($arr,$arr1,$arrN);//递归替换$arr独有保持不变,$arr1独有则追加,同时存在则替换(先arr1替换,完事后arrN再替换)即支持多维替换 ~~~ $arr=['a'=>1,'b'=>2,'c'=>3,4]; $arr1=['a'=>100]; $arrN=['d'=>5]; $ar=array_replace_recursive($arr,$arr1,$arrN); array(5) { ["a"]=> int(100) ["b"]=>int(2) ["c"]=>int(3) [0]=>int(4) ["d"]=>int(5) } ~~~ ### **array_replace**($arr ,$arr1,$arrN )   (用法同**array_replace_recursive**)一维 数组替换 不能递归替换 ## **数组元素查找** ### **array_search**($search_value, `$arr`, false ); 一维数组中查找指定元素 返回键名 (只返回匹配的第一个) ### **array_keys**($arr , `$search_value=null,false` );//返回一维数组元素值相同的所有键名 ### **array_keys**($arr);//返回一维数组的所有键名 ~~~ $array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red',4=>"green"); $key = array_search('green', $array); // $key = 2; $keys=array_keys($array,'green');//[2,4] ~~~ ### **array_values**($arr);    返回数组中所有的值  ### **in_array**($search_value, $arr, FALSE【严格匹配】);   检查一维数组里是否存在给定的值    ### [array_key_exists()](https://www.php.net/manual/zh/function.array-key-exists.php) - 检查数组一维里是否有指定的键名或索引(返回bolean)  ## **求和** ## **array_sum**()  返回一维数组所有的值总和 ## **数组去重** ### **array_unique($arr)** ### **array_flip**(array_flip($arr)); 这样便可以删除重复元素。 比上面的要效率; 原理:array_flip()交换数组中的键和值但是php键是唯一的而且数组中可以有相同的值如果交换键和值的话最后一个相同的值或取代前面相同的值进行交换 ## **关联数组变索引数组:** ### **array_values($arr)** 返回含所有值的索引数组 ## **php数组差集交集并集** ### **差集:(取独有)**                                返回arr中有某个值而其他它arr1~arrN无此值或键或键值的结果 array\_​diff\_​key                        计算差集(系统函数比较键) array\_​diff                                计算差集(系统函数比较值) array\_​diff\_​assoc                     计算差集(系统函数比较键和值) array\_​diff\_​uassoc                   计算差集(系统函数比较值,自定义函数比较键) array\_​diff\_​ukey                       计算差集(自定义函数比较键)要么全是关联数组要么全是索引数组 array\_​udiff\_​assoc                   计算差集(系统函数比较键,自定义函数比较值) array\_​udiff\_​uassoc                 计算差集(自定义函数比较值和键) array\_​udiff                               计算差集(自定义函数比较值) ### **交集(取共同)**                                      返回arr中有某个值且其他它arr1~arrN也有此键或值或键值的结果 array\_​intersect\_​key                 计算交集(系统函数比较键) array\_​intersect                        计算交集(系统函数比较值) array\_​intersect\_​assoc             计算交集(系统函数比较键和值) array\_​intersect\_​uassoc           计算交集(系统函数比较键和值) array\_​intersect\_​ukey               计算交集(系统函数比较值,自定义函数比较键) array\_​uintersect\_​assoc           计算交集(系统函数比较键,自定义函数比较值) array\_​uintersect\_​uassoc         计算交集(自定义函数比较值和键) array\_​uintersect                      计算交集(自定义函数比较值) ### **并集**(取全部) array\_merge($arr1,$arrN); array\_merge\_recursive ($array1 ,$arrN); //有相同字符串的key则合并,其余追加(键值相同不覆盖) ## **数组循环比较** 一般加引用要慢点 foreach 与array\_walk相比 array\_walk多出一个函数调用 效率 for≈foreach(无key) >foreach(有key)>foreach(有key+引用)>foreach(无key+引用)>array\_walk(函数在外) >array\_walk(函数在内) >array\_walk(引用) >array\_map ~~~ foreach是最快的,因为php的array内部元素之间有指针,就是list,直接指向下个元素的内存地址,所以遍历速度很快 for的问题在于,每次都要做一个hash table的查询。 array_walk/array_map 遍历的方式和foreach一样的,慢是慢在回调函数 ~~~  但是如果在循环里有函数调用array\_walk的效率是最高的、 ~~~ $max = 1000000; $test_arr = range(0, $max); $temp=0; echo "<br>"; echo "<br>"; echo "<br>"; /*for 的方法*/ $t1 = microtime(true); for ($i = 0; $i < $max; $i++) { demo($i); } $t2 = microtime(true); $t = $t2 - $t1; echo "就使用for, 花费: {$t}<br>\n"; /*foreach*/ $t1 = microtime(true); foreach ($test_arr as $key => $value) { demo($value); } $t2 = microtime(true); $t = $t2 - $t1; echo "就使用foreach有key, 花费: {$t}<br>\n"; /*foreach*/ $t1 = microtime(true); foreach ($test_arr as $value) { demo($value); } $t2 = microtime(true); $t = $t2 - $t1; echo "就使用foreach无key, 花费: {$t}<br>\n"; /*foreach*/ $t1 = microtime(true); foreach ($test_arr as &$value) { demo($value); } $t2 = microtime(true); $t = $t2 - $t1; echo "就使用foreach无key+引用, 花费: {$t}<br>\n"; /*foreach*/ $t1 = microtime(true); foreach ($test_arr as $key => &$value) { demo($value); } $t2 = microtime(true); $t = $t2 - $t1; echo "就使用foreach有key+引用, 花费: {$t}<br>\n"; /*array_walk*/ $t1 = microtime(true); array_walk($test_arr ,function(&$itemValue,$key){ demo($itemValue); }); $t2 = microtime(true); $t = $t2 - $t1; echo "array_walk+引用, 花费: {$t}<br>\n"; /*array_walk*/ $t1 = microtime(true); array_walk($test_arr ,function($itemValue,$key){ demo($itemValue); }); $t2 = microtime(true); $t = $t2 - $t1; echo "array_walk, 花费: {$t}<br>\n"; /*array_walk*/ $t1 = microtime(true); array_walk($test_arr ,'arrayWalkCallBack'); $t2 = microtime(true); $t = $t2 - $t1; echo "array_walk 函数在外, 花费: {$t}<br>\n"; function demo($num) { $test=new stdClass(); $test->name='dash'; $test->age=28; $test->like='乒乓'; $test->code=$num; return $test; } function arrayWalkCallBack($itemValue,$key){ demo($itemValue); } ~~~ ### **array_map** array_map的主要作用是通过自定义函数对数组的值进行另外处理,另外可以做为对多个数组的相对应单元进行数据合并处理等。 * 1,array_map在调用的方法中取不到数组的键名,特别是只传递一个数组的时候,它完全是处理值。 * 2,只传递一个数组给array\_map最后得到的数组键名不变,但是如果传递多个数组则键名全都自动变成重新排列的数字索引。 * 3,回调函数是平行作用于相应的单元上的, 所以使用多个数组时,它们的长度应该相同。不然则最短的一个将被用空的单元扩充。 ~~~ $data =[ 226495 => '2018-12-25 10:47:47', 226519 => '2018-12-25 10:47:45', 226499 => '2018-12-25 10:47:44', 226604 => '2019-01-11 11:21:51', 226517 => '2018-12-25 10:47:36', 226630 => '2019-01-11 11:17:56', 226493 => '2018-12-25 10:47:34', 226502 => '2018-12-25 10:47:32', ]; $datas =[ 1=>'2018-12-25 10:47:47', 2=>'2018-12-25 10:47:45', 3=>'2018-12-25 10:47:44', 4=>'2019-01-11 11:21:51', 4=>'2018-12-25 10:47:36', 6=>'2019-01-11 11:17:56', 7=>'2018-12-25 10:47:34', 8=>'2018-12-25 10:47:32', ]; //调用array_map对单个数组值进行处理,索引能保持 $res1=array_map(function($val){ //只获取时分秒 return explode(' ', $val)[1]; }, $data); var_export($res1); /* array ( 226495 => '10:47:47', 226519 => '10:47:45', 226499 => '10:47:44', 226604 => '11:21:51', 226517 => '10:47:36', 226630 => '11:17:56', 226493 => '10:47:34', 226502 => '10:47:32', ) */ //传递多个数组后返回的数组键名重新进行数字索引 $res2=array_map(function($value,$value2){ //只获年月日 return current(explode(' ', $value)); }, $data, $datas); var_export($res2); /* array ( 0 => '2018-12-25', 1 => '2018-12-25', 2 => '2018-12-25', 3 => '2019-01-11', 4 => '2018-12-25', 5 => '2019-01-11', 6 => '2018-12-25', 7 => '2018-12-25', ) */ //传递多个数组进行数据重组处理 $res3=array_map(function($value,$value2){ return explode(' ', $value)[1].'=='.$value2; }, $data, $datas); var_export($res3); /**数据怎么错乱了?? array ( 0 => '10:47:47==2018-12-25 10:47:47', 1 => '10:47:45==2018-12-25 10:47:45', 2 => '10:47:44==2018-12-25 10:47:44', 3 => '11:21:51==2018-12-25 10:47:36', 4 => '10:47:36==2019-01-11 11:17:56', 5 => '11:17:56==2018-12-25 10:47:34', 6 => '10:47:34==2018-12-25 10:47:32', 7 => '10:47:32==', ) / ~~~ 实战:三个维度的数据合并 ``` //三个维度的数据合并 $names = array('zhangsan', 'lisi', 'wangwu'); $sex = array("man", "sex", "man"); $age = array(20, 25, 28); $users = array_map(null, $names, $sex, $age); print_r($users); //输出结果如下: Array ( [0] => Array ( [0] => zhangsan [1] => 20 [2] => man ) [1] => Array ( [0] => lisi [1] => 25 [2] => sex ) [2] => Array ( [0] => wangwu [1] => 28 [2] => man ) ) ``` ### [**array_walk**()](https://www.php.net/manual/zh/function.array-walk.php)( array &$array , callable $funcname [, mixed $userdata = NULL ] ) - 使用用户自定义函数对数组中的每个元素做回调处理 1, array\_walk同时能拿到数据的键和值 2,array\_walk并不返回新数组,只返回标识操作是否成功的布尔值 3,因为array\_walk不返回数组,array\_walk的使用更倾向于在原数组上进行数据修改处理,当然也可以在另外一个变量上处理。 ``` $names = array(1=>'zhangsan',2=> 'lisi',3=> 'wangwu'); //不修改原数组,直接显示 $result = array_walk($names, function($value, $key){ echo '第',$key,'名:',$value,'<br>'; }); var_dump($result); /* 第1名:zhangsan 第2名:lisi 第3名:wangwu bool(true) */ //地址引用,直接修改 $result2 = array_walk($names, function(&$value, $key){ $value = '第'.$key.'名:'.$value; }); print_r($names); var_dump($result2); /* Array ( [1] => 第1名:zhangsan [2] => 第2名:lisi [3] => 第3名:wangwu ) bool(true) */ //地址引用,直接修改, 附带其它数据 $result3 = array_walk($names, function(&$value, $key, $extra){ $value = $extra .$value; }, $extra="大家好,"); print_r($names); var_dump($result3); /* Array ( [1] => 大家好,第1名:zhangsan [2] => 大家好,第2名:lisi [3] => 大家好,第3名:wangwu ) bool(true) */ ``` **通过上面对array\_map和array\_walk的使用,综合起来对比区别如下:** **1,array\_walk主要是针对单个数组进行处理,array\_map可以处理单个,也可以把多个数组结合一起处理。** **2,array\_map的作用更多的是得到一个新数组,array\_walk更多的是想做一些job, 只要结果执行成功了即行。** **3,对单个数组进行操作时,array\_map和array\_walk功能很像,区别在于array\_map是取得返回的数组;而array\_walk因为不返回所以通过地址引用在原数组上修改以实现“返回”。** **4,对多个数组处理时array\_map比array\_walk更适合。** ### [**array_​walk_​recursive**](https://www.php.net/manual/zh/function.array-walk-recursive.php "array_​walk_​recursive")($arr , `$callback` \[, [mixed](https://www.php.net/manual/zh/language.pseudo-types.php#language.types.mixed) $userdata = NULL ])  数组循环之递归的为每个数组元素调用callback 与array\_walk不同的是,array\_walk\_recursive函数会递归到更深层的数组中去,即对多维数组,array\_walk\_recursive会深入到更深层的数组键值中去处理。有一点需要要特别注意的是传入给array\_walk\_recursive的数组参数中任何值为 array 的键都不会被传递到回调函数中去如: ``` $fruits = ['sweet' => ['a' => 'apple', 'b' => 'banana'], 'sour' => 'lemon']; array_walk_recursive($fruits, function($item, $key){ echo "$key => $item\n"; }); /**注意上例中的键 'sweet' 并没有显示出来。任何其值为 array 的键都不会被传递到回调函数中去 就像这里sweet下标对应的值位数组,所以这里不会返回 a => apple b => banana sour => lemon **/ ``` **示例:多维变一维** ``` $array=[ 1=>[2,5=>[4,2],[7,8=>[3,6]],5], 2=>4 ]; var_export($array); $arr=[]; array_walk_recursive($array, function($k){ global $arr; $arr[]=$k; }); print_r($arr);//Array ( [0] => 2 [1] => 4 [2] => 2 [3] => 7 [4] => 3 [5] => 6 [6] => 5 [7] => 4 ) ``` **额外参数:** ``` $fruits = ['sweet' => ['a' => 'apple', 'b' => 'banana'], 'sour' => 'lemon']; $extra1=1; $extra2=2; array_walk_recursive($fruits, function($item, $key, $extra){ echo "$key => $item\n $extra[0]<==>$extra[1]\n"; }, [$extra1,$extra2]); ``` **外部变量持久化** ``` $arr = [ 'one' => ['one_one' => 'A', 'one_two' => 'B'], 'two' => 2 ]; $counter = 0; //默认情况下,外部变量在回调函数中保存不了的 array_walk_recursive( $arr, function($value, $key, $counter) { $counter++; echo $value." :". $counter"; }, $counter); echo "counter :". $counter; /** 结果: A : 1 B : 1 2 : 1 counter : 0 **/ //仅在相同的数组节点中持久存在使用引用 array_walk_recursive( $arr, function($value, $key, &$counter) { $counter++; echo $value." :". $counter"; }, $counter); echo "counter :". $counter; /** 结果: A : 1 B : 2 2 : 1 counter : 0 **/ //完全持久的化使用"use"关键字 array_walk_recursive( $arr, function($value, $key) use (&$counter) { $counter++; echo $value." :". $counter"; }, $counter); echo "counter :". $counter; /** 结果: A : 1 B : 2 2 : 3 counter : 3 **/ ``` ## 所有键名转小写或者大写 ### array_​change_​key_​case($arr , CASE_LOWER | CASE_UPPER): ## [返回指定【下标】的值组成的新数组(返回的值还可以指定下标)](https://www.php.net/manual/zh/function.array-column.php "array_​column") [array\_​column($arr, $key=null ,$newArrKey=null);//返回指定【下标key】的值组成的新数组(第三个参数指定返回值的下标)](https://www.php.net/manual/zh/function.array-column.php "array_​column") ``` array_column ($arr, null ,null);//返回指定【下标】的值(返回的值还可以指定下标) /* $arr=[ [ 'id' => 21, 'first_name' => 'John', 'last_name' => 'Doe', ], [ 'id' => 35, 'first_name' => 'John', 'last_name' => 'Doe', [ 'id'=>'50' ] ] ] array_column($records, 'first_name',null); $arr=[ [John,Peter] ]; array_column($records, 'first_name','id'); $arr=[ [21=>John,35=>Peter] ]; array_column($records, null,'id'); $arr=[ 21=>[ 'id' => 21, 'first_name' => 'John', 'last_name' => 'Doe', ], 35=>[ 'id' => 35, 'first_name' => 'John', 'last_name' => 'Doe', [ 'id'=>'50' ] ] ] */ ``` ## [array\_​count\_​values](https://www.php.net/manual/zh/function.array-count-values.php "array_​count_​values")($arr)   计算数组中每个值出现的次数 返回原数组的值为键 出现次数为值的数组 ## [array\_​fill\_​keys($keysArr, $mixed\_value);](https://www.php.net/manual/zh/function.array-fill-keys.php "array_​fill_​keys")  用户指定键和值来填充数组 ~~~ $keys = array('foo', 5, 10, 'bar');//第一个参数数组的值作为填充数组的键,第二个参数作为值 array_fill_keys($keys, 'banana'); //['foo'=>'banana',5=>'banana',10=>'banana','bar'=>'banana'] $keys = array('foo', 5); $value=array('banana','apple'); $a=array_fill_keys($keys,$value); //['foo'=>['banana','apple'],5=>['banana','apple']] ~~~ ## [array\_​fill](https://www.php.net/manual/zh/function.array-fill.php "array_​fill")($start\_index , $num(超过这个给定数组的长度就不填充了) ,$mixed\_value);给定的值填充数组 [array\_​flip](https://www.php.net/manual/zh/function.array-flip.php "array_​flip") [array\_​intersect\_​assoc](https://www.php.net/manual/zh/function.array-intersect-assoc.php "array_​intersect_​assoc") [array\_​intersect\_​key](https://www.php.net/manual/zh/function.array-intersect-key.php "array_​intersect_​key") [array\_​intersect\_​uassoc](https://www.php.net/manual/zh/function.array-intersect-uassoc.php "array_​intersect_​uassoc") [array\_​intersect\_​ukey](https://www.php.net/manual/zh/function.array-intersect-ukey.php "array_​intersect_​ukey") [array\_​intersect](https://www.php.net/manual/zh/function.array-intersect.php "array_​intersect") [array\_​key\_​exists](https://www.php.net/manual/zh/function.array-key-exists.php "array_​key_​exists") [array\_​key\_​first](https://www.php.net/manual/zh/function.array-key-first.php "array_​key_​first") [array\_​key\_​last](https://www.php.net/manual/zh/function.array-key-last.php "array_​key_​last") [array\_​keys](https://www.php.net/manual/zh/function.array-keys.php "array_​keys") [array\_​map](https://www.php.net/manual/zh/function.array-map.php "array_​map") [array\_​merge\_​recursive](https://www.php.net/manual/zh/function.array-merge-recursive.php "array_​merge_​recursive") [array\_​merge](https://www.php.net/manual/zh/function.array-merge.php "array_​merge") [array\_​pad](https://www.php.net/manual/zh/function.array-pad.php "array_​pad") [array\_​pop](https://www.php.net/manual/zh/function.array-pop.php "array_​pop") [array\_​product](https://www.php.net/manual/zh/function.array-product.php "array_​product") [array\_​push](https://www.php.net/manual/zh/function.array-push.php "array_​push") [array\_​rand](https://www.php.net/manual/zh/function.array-rand.php "array_​rand") [array\_​reduce](https://www.php.net/manual/zh/function.array-reduce.php "array_​reduce") [array\_​replace\_​recursive](https://www.php.net/manual/zh/function.array-replace-recursive.php "array_​replace_​recursive") [array\_​replace](https://www.php.net/manual/zh/function.array-replace.php "array_​replace") [array\_​reverse](https://www.php.net/manual/zh/function.array-reverse.php "array_​reverse") [array\_​search](https://www.php.net/manual/zh/function.array-search.php "array_​search") [array\_​shift](https://www.php.net/manual/zh/function.array-shift.php "array_​shift") [array\_​slice](https://www.php.net/manual/zh/function.array-slice.php "array_​slice") [array\_​splice](https://www.php.net/manual/zh/function.array-splice.php "array_​splice") [array\_​sum](https://www.php.net/manual/zh/function.array-sum.php "array_​sum") [array\_​udiff\_​assoc](https://www.php.net/manual/zh/function.array-udiff-assoc.php "array_​udiff_​assoc") [array\_​udiff\_​uassoc](https://www.php.net/manual/zh/function.array-udiff-uassoc.php "array_​udiff_​uassoc") [array\_​udiff](https://www.php.net/manual/zh/function.array-udiff.php "array_​udiff") [array\_​uintersect\_​assoc](https://www.php.net/manual/zh/function.array-uintersect-assoc.php "array_​uintersect_​assoc") [array\_​uintersect\_​uassoc](https://www.php.net/manual/zh/function.array-uintersect-uassoc.php "array_​uintersect_​uassoc") [array\_​uintersect](https://www.php.net/manual/zh/function.array-uintersect.php "array_​uintersect") [array\_​unique](https://www.php.net/manual/zh/function.array-unique.php "array_​unique") [array\_​unshift](https://www.php.net/manual/zh/function.array-unshift.php "array_​unshift") [array\_​values](https://www.php.net/manual/zh/function.array-values.php "array_​values") [array\_​walk\_​recursive](https://www.php.net/manual/zh/function.array-walk-recursive.php "array_​walk_​recursive") [array\_​walk](https://www.php.net/manual/zh/function.array-walk.php "array_​walk") [array](https://www.php.net/manual/zh/function.array.php "array") [arsort](https://www.php.net/manual/zh/function.arsort.php "arsort") [asort](https://www.php.net/manual/zh/function.asort.php "asort") [compact](https://www.php.net/manual/zh/function.compact.php "compact") [count](https://www.php.net/manual/zh/function.count.php "count") [current](https://www.php.net/manual/zh/function.current.php "current") [end](https://www.php.net/manual/zh/function.end.php "end") [extract](https://www.php.net/manual/zh/function.extract.php "extract") [in\_​array](https://www.php.net/manual/zh/function.in-array.php "in_​array") [key\_​exists](https://www.php.net/manual/zh/function.key-exists.php "key_​exists") [key](https://www.php.net/manual/zh/function.key.php "key") [krsort](https://www.php.net/manual/zh/function.krsort.php "krsort") [ksort](https://www.php.net/manual/zh/function.ksort.php "ksort") [list](https://www.php.net/manual/zh/function.list.php "list") [natcasesort](https://www.php.net/manual/zh/function.natcasesort.php "natcasesort") [natsort](https://www.php.net/manual/zh/function.natsort.php "natsort") [next](https://www.php.net/manual/zh/function.next.php "next") [pos](https://www.php.net/manual/zh/function.pos.php "pos") [prev](https://www.php.net/manual/zh/function.prev.php "prev") [range](https://www.php.net/manual/zh/function.range.php "range") [reset](https://www.php.net/manual/zh/function.reset.php "reset") [rsort](https://www.php.net/manual/zh/function.rsort.php "rsort") [shuffle](https://www.php.net/manual/zh/function.shuffle.php "shuffle") [sizeof](https://www.php.net/manual/zh/function.sizeof.php "sizeof") [sort](https://www.php.net/manual/zh/function.sort.php "sort") [uasort](https://www.php.net/manual/zh/function.uasort.php "uasort") [uksort](https://www.php.net/manual/zh/function.uksort.php "uksort") [usort](https://www.php.net/manual/zh/function.usort.php "usort") Deprecated [each](https://www.php.net/manual/zh/function.each.php "each") 检测方法是否存在:method\_exists() 检测方法是否存在且(外部)可调用:is\_callable() ~~~ class Test { public function PublicMethod(){} protected function ProtectedMethod(){} private function PrivateMethod(){} public static function PublicStaticMethod(){} protected static function ProtectedStaticMethod(){} private static function PrivateStaticMethod(){} } $test = new Test(); $callbacks = array( array($test, 'PublicMethod'),//true array($test, 'ProtectedMethod'),//false array($test, 'PrivateMethod'),//false array($test, 'PublicStaticMethod'),//true array($test, 'ProtectedStaticMethod'),//false array($test, 'PrivateStaticMethod'),//false array('Test', 'PublicMethod'),//true array('Test', 'ProtectedMethod'),//false array('Test', 'PrivateMethod'),//false array('Test', 'PublicStaticMethod'),//true array('Test', 'ProtectedStaticMethod'),//false array('Test', 'PrivateStaticMethod'),//false ); foreach ($callbacks as $callback){ //var_dump($callback); echo'is_callable:'; var_dump(is_callable($callback)); } class Test { public function PublicMethod(){} protected function ProtectedMethod(){} private function PrivateMethod(){} public static function PublicStaticMethod(){} protected static function ProtectedStaticMethod(){} private static function PrivateStaticMethod(){} } $test = new Test(); $callbacks = array( array($test, 'PublicMethod'),//true array($test, 'ProtectedMethod'),//true array($test, 'PrivateMethod'),//true array($test, 'PublicStaticMethod'),//true array($test, 'ProtectedStaticMethod'),//true array($test, 'PrivateStaticMethod'),//true array('Test', 'PublicMethod'),//true array('Test', 'ProtectedMethod'),//true array('Test', 'PrivateMethod'),//true array('Test', 'PublicStaticMethod'),//true array('Test', 'ProtectedStaticMethod'),//true array('Test', 'PrivateStaticMethod'),//true ); foreach ($callbacks as $callback){ //var_dump($callback); echo'method_exists:'; var_dump(method_exists($callback[0], $callback[1])); } ~~~ 类或对象的相关函数 [\_​\_​autoload](https://www.php.net/manual/zh/function.autoload.php "_​_​autoload") [class\_​alias](https://www.php.net/manual/zh/function.class-alias.php "class_​alias") [class\_​exists](https://www.php.net/manual/zh/function.class-exists.php "class_​exists") [get\_​called\_​class](https://www.php.net/manual/zh/function.get-called-class.php "get_​called_​class") [get\_​class\_​methods](https://www.php.net/manual/zh/function.get-class-methods.php "get_​class_​methods") [get\_​class\_​vars](https://www.php.net/manual/zh/function.get-class-vars.php "get_​class_​vars") [get\_​class](https://www.php.net/manual/zh/function.get-class.php "get_​class") [get\_​declared\_​classes](https://www.php.net/manual/zh/function.get-declared-classes.php "get_​declared_​classes") [get\_​declared\_​interfaces](https://www.php.net/manual/zh/function.get-declared-interfaces.php "get_​declared_​interfaces") [get\_​declared\_​traits](https://www.php.net/manual/zh/function.get-declared-traits.php "get_​declared_​traits") [get\_​object\_​vars](https://www.php.net/manual/zh/function.get-object-vars.php "get_​object_​vars") [get\_​parent\_​class](https://www.php.net/manual/zh/function.get-parent-class.php "get_​parent_​class") [interface\_​exists](https://www.php.net/manual/zh/function.interface-exists.php "interface_​exists") [is\_​a](https://www.php.net/manual/zh/function.is-a.php "is_​a") [is\_​subclass\_​of](https://www.php.net/manual/zh/function.is-subclass-of.php "is_​subclass_​of") [method\_​exists( $className\_str|`$object`  ,`$methodName_str` )](https://www.php.net/manual/zh/function.method-exists.php "method_​exists")   检查类的方法是否存在 [property\_​exists](https://www.php.net/manual/zh/function.property-exists.php "property_​exists") [trait\_​exists](https://www.php.net/manual/zh/function.trait-exists.php "trait_​exists") Deprecated [call\_​user\_​method\_​array](https://www.php.net/manual/zh/function.call-user-method-array.php "call_​user_​method_​array") [call\_​user\_​method](https://www.php.net/manual/zh/function.call-user-method.php "call_​user_​method") **为什么我在点击浏览器的后退按钮后,所有字段的信息都被清空了?** 提交表单的页面使用了session\_start();该函数会强制当前页面不被缓存,表单提交错误数据时后在返回提交页面表单使内容被清空,要想保留表单的数据怎么办? 第一种方法:使用session\_cache\_limiter('private, must-revalidate')函数,但是要值得注意的是session\_cache\_limiter()方法要写在session\_start()方法之前才有用; 第二种方法:header('Cache-control: private, must-revalidate');//支持页面回跳;在session\_start()方法之后用 \_\_DIR\_\_和dirname(\_\_FILE\_\_);都是获取当前脚本所在目录的\_\_DIR\_\_效率高但是实在php5.3加入的所以用时需要注意