1.array_reduce 一个神奇的函数
例:将二维数组变为一维数组
//例:将二维数组变为一维数组
//$ids 初始值为array(),function 返回值将其重置,第二个参数为$two_arr中的值的遍历
$two_arr = array('1'=>array(0=>'a',1=>'b',2=>'c'),
'2'=>array(3=>'d',4=>'e',5=>'f',6=>'g')
);
$total = array_reduce($two_arr, function($ids, $value){
return array_merge($ids, array_values($value));
}, array());
print_r('<pre>');
print_r($total);
输出:Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
[6] => g
)
PS: 将任意维度数组转为一维数组 原文:https://wosn.net/791.html
<?php
# 应用场景例转义数组的字符为特定格式
$result = [];
$user = array(
'a' => array(100, 'ty.com/test.php'),
'b' => array(
'c' => array(101, '39.105.143.144/index.php'),
),
);
array_walk_recursive($user, function($value) use (&$result) {
array_push($result, urlencode($value));
});
print_r('<pre>');
var_dump($result);
结果:
array(4) {
[0]=>
string(3) "100"
[1]=>
string(17) "ty.com%2Ftest.php"
[2]=>
string(3) "101"
[3]=>
string(26) "39.105.143.144%2Findex.php"
}
2.array_rand( [array] ) 返回随机的键名
$res = array_rand(array(1=>'a', 2=>'b'));
var_dump($res); #随机返回1和2