$arr = ['Client'=>'jQuery','Server'=>'PHP'];
array_walk($arr, function($v, $k) {
echo "键:$k 值:$v\n";
});
比如去除数组$arr元素的前后空白:
array_walk($arr, function(&$v) { $v = trim($v); });
foreach($arr as &$v) { $v = trim($v); }
array_filter: 用回调函数过滤数组中的单元,返回过滤后的数组
var_export(
array_filter([1, 2, 3], function($v) {
return $v > 1;
})
);
和
foreach([1, 2, 3] as $k => $v) {
if($v > 1) {
$tmp[$k] = $v;
}
}
var_export($tmp);
都输出:
array (
1 => 2,
2 => 3,
)
PHP数组映射化简(MapReduce):
array_map/array_reduce
array_map: 将回调函数作用到给定数组的单元上
var_export(
array_map(function ($v) {
return $v * $v;
}, [1, 2, 3])
);
和
foreach([1, 2, 3] as $v) {
$tmp[] = $v * $v;
}
var_export($tmp);
都输出:
array (
0 => 1,
1 => 4,
2 => 9,
)
array_reduce: 用回调函数迭代地将数组简化(reduce)为单一的值
//输出16,即10+1+2+3,其中10作为初始值.
echo array_reduce([1, 2, 3], function($result, $item) {
$result = $result + $item;
return $result;
}, 10);
用foreach表达:
$result = 10;
foreach([1, 2, 3] as $v) {
$result = $result + $v;
}
echo $result;
执行效果都一样,但是具体的用函数快还是用foreach快些啊
array_walk相当于foreach:
$arr = ['Client'=>'jQuery','Server'=>'PHP'];
array_walk($arr, function($v, $k) {
echo "键:$k 值:$v\n";
});
比如去除数组$arr元素的前后空白:
array_walk($arr, function(&$v) { $v = trim($v); });
foreach($arr as &$v) { $v = trim($v); }
array_filter: 用回调函数过滤数组中的单元,返回过滤后的数组
var_export(
array_filter([1, 2, 3], function($v) {
return $v > 1;
})
);
和
foreach([1, 2, 3] as $k => $v) {
if($v > 1) {
$tmp[$k] = $v;
}
}
var_export($tmp);
都输出:
array (
1 => 2,
2 => 3,
)
PHP数组映射化简(MapReduce):
array_map/array_reduce
array_map: 将回调函数作用到给定数组的单元上
var_export(
array_map(function ($v) {
return $v * $v;
}, [1, 2, 3])
);
和
foreach([1, 2, 3] as $v) {
$tmp[] = $v * $v;
}
var_export($tmp);
都输出:
array (
0 => 1,
1 => 4,
2 => 9,
)
array_reduce: 用回调函数迭代地将数组简化(reduce)为单一的值
//输出16,即10+1+2+3,其中10作为初始值.
echo array_reduce([1, 2, 3], function($result, $item) {
$result = $result + $item;
return $result;
}, 10);
用foreach表达:
$result = 10;
foreach([1, 2, 3] as $v) {
$result = $result + $v;
}
echo $result;
执行效果都一样,但是具体的用函数快还是用foreach快些啊