PHP array_map()函数与示例

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值