array_map 返回值,array_walk是处理过程
// intval、strtolower 可以转换数组值的类型,或调用其他内置函数,很方便了 array_map("intval", explode(',', $str)); // 可配合验证参数是否是int,来抛出全局异常 array_walk()
// 用array_walk给二维数组添加元素
$a = [['a' => '1', 'c' => '333']];
array_walk($a, function (&$v, $k) {
$v['d'] = '5555';
});
//Array
//(
// [0] => Array
// (
// [a] => 1
// [c] => 333
// [d] => 5555
// )
//)
// 用array_map给一维数组的每个值拼接字符串得到新数组
$b = $c = ['a' => '1', 'c' => '333'];
$d = array_map(function ($v) {
return $v . '.00';
}, $b);
//Array
//(
// [a] => 1.00
// [c] => 333.00
//)
// 用array_reduce拼接一维数组,我感觉还不如直接 $m = 'begin-' . implode('-', $c);
$m = array_reduce($c, function ($v1, $v2) {
return $v1 . "-" . $v2;
}, 'begin');
//begin-1-333
//二维数组转一维数组
$a = [
[
['name' => 'zs'],
['name' => 'li'],
],
[
['name' => 'fz'],
['name' => 'ww'],
]
];
print_r(array_reduce($a, 'array_merge', []));
$a1=array("Horse", "Dog", "Cat");
$a2=array("Cow", "Dog", "Rat");
$a3 = array_map(function ($v1, $v2)
{
return "{$v1} - {$v2}";
}, $a1, $a2);
print_r($a3);
/*
Array
(
[0] => Horse - Cow
[1] => Dog - Dog
[2] => Cat - Rat
)
*/
$a = array("a"=>"red","b"=>"green","c"=>"blue");
array_walk($a, function ($value, $key, $p)
{
echo "$key $p $value<br>";
}, "has the value");
/*
a has the value red
b has the value green
c has the value blue
*/