PHP array_map()函数 (PHP array_map() function)
array_map() function is used to apply operations on each array values (elements) based on the given function, it sends each value of an array to the given function and returns a new array with the calculated values.
array_map()函数用于基于给定函数对每个数组值(元素)应用操作,它将数组的每个值发送给给定函数,并返回包含计算值的新数组。
Syntax:
句法:
array_map(function, array1, [array2], ...);
Here,
这里,
function is the name of the function, that will be used to apply operation on each value of the given array.
function是函数的名称,将用于对给定数组的每个值进行操作。
array1 is an array on which we have to perform the operation.
array1是我们必须在其上执行操作的数组。
array2, ... are optional parameters, we can specify multiple arrays too.
array2,...是可选参数,我们也可以指定多个数组。
Examples:
例子:
Input:
$arr = array(10, 20, 30, 40, 50);
Function:
function getSquare($value)
{
return ($value*$value);
}
Function call:
array_map("getSquare", $arr);
Output:
Array
(
[0] => 100
[1] => 400
[2] => 900
[3] => 1600
[4] => 2500
)
PHP code 1: Getting the squares and cubes of the all values
PHP代码1:获取所有值的平方和立方
<?php
//functions
function getSquare($value)
{
return ($value*$value);
}
function getCube($value)
{
return ($value*$value*$value);
}
//array
$arr = array(10, 20, 30, 40, 50);
//new array of squares of the array's values
$arr_sqr = array_map("getSquare", $arr);
//new array of squares of the array's values
$arr_cube = array_map("getCube", $arr);
//printing
print_r ($arr_sqr);
print_r ($arr_cube);
?>
Output
输出量
Array
(
[0] => 100
[1] => 400
[2] => 900
[3] => 1600
[4] => 2500
)
Array
(
[0] => 1000
[1] => 8000
[2] => 27000
[3] => 64000
[4] => 125000
)
PHP code 2: Finding sum of the values of two arrays
PHP代码2:查找两个数组的值之和
<?php
//function to add values of two arrays
function addValues($value1, $value2)
{
return ($value1 + $value2);
}
//arrays
$arr1 = array(10, 20, 30, 40, 50);
$arr2 = array(100, 200, 300, 400, 500);
$result = array_map("addValues", $arr1, $arr2);
print_r ($result);
?>
Output
输出量
Array
(
[0] => 110
[1] => 220
[2] => 330
[3] => 440
[4] => 550
)
翻译自: https://www.includehelp.com/php/array_map-function-with-example.aspx