// 初始化一组数据
$data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// 对数组中的每个元素 + 5
array_map(function ($item){
echo $item + 5 . ' ';
}, $data);
echo '';
// 对数组中的每个元素 + 5, 并将结果返回出去
$new_data = [];
array_map(function ($item) use (& $new_data){
$new_data[] = $item + 5;
}, $data);
print_r($new_data);
结果:
6 7 8 9 10 11 12 13 14 15
Array ( [0] => 6 [1] => 7 [2] => 8 [3] => 9 [4] => 10 [5] => 11 [6] => 12 [7] => 13 [8] => 14 [9] => 15 )
// 初始化一组数据
$data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
print_r($data); echo '';
// 将数组进行分段,每段5个元素
$new_data = array_chunk($data, 5);
print_r($new_data);
结果
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 [9] => 10 )
Array ( [0] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) [1] => Array ( [0] => 6 [1] => 7 [2] => 8 [3] => 9 [4] => 10 ) )
// 初始化一组数据
$data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// 每5个一组进行分批处理,对数组中的每个元素 + 10
array_map(function ($sub_arr){
foreach ($sub_arr as $item) {
echo ($item + 10) . ' ';
}
echo '';
}, array_chunk($data, 5));
结果:
11 12 13 14 15
16 17 18 19 20