@Chiang
2020-01-17T14:17:20.000000Z
字数 2278
阅读 509
PHP-Array
array_map — 为数组的每个元素应用回调函数
array_map ( callable $callback , array $array1 [, array $... ] ) : array
array_map():返回数组,是为 array1 每个元素应用 callback函数之后的数组。
callback 函数形参的数量和传给 array_map() 数组数量,两者必须一样
。
- callback
回调函数,应用到每个数组里的每个元素。- array1
数组,遍历运行 callback 函数。- ...
数组列表,每个都遍历运行 callback 函数。
返回数组,
包含 callback 函数处理之后 array1 的所有元素
。
<?php
function cube($n)
{
return($n * $n * $n);
}
$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
?>
这使得 $b 成为:
Array
(
[0] => 1
[1] => 8
[2] => 27
[3] => 64
[4] => 125
)
<?php
$func = function($value) {
return $value * 2;
};
print_r(array_map($func, range(1, 5)));
?>
Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
[4] => 10
)
<?php
function show_Spanish($n, $m)
{
return("The number $n is called $m in Spanish");
}
function map_Spanish($n, $m)
{
return(array($n => $m));
}
$a = array(1, 2, 3, 4, 5);
$b = array("uno", "dos", "tres", "cuatro", "cinco");
$c = array_map("show_Spanish", $a, $b);
print_r($c);
$d = array_map("map_Spanish", $a , $b);
print_r($d);
?>
以上例程会输出:
// printout of $c
Array
(
[0] => The number 1 is called uno in Spanish
[1] => The number 2 is called dos in Spanish
[2] => The number 3 is called tres in Spanish
[3] => The number 4 is called cuatro in Spanish
[4] => The number 5 is called cinco in Spanish
)
// printout of $d
Array
(
[0] => Array
(
[1] => uno
)
[1] => Array
(
[2] => dos
)
[2] => Array
(
[3] => tres
)
[3] => Array
(
[4] => cuatro
)
[4] => Array
(
[5] => cinco
)
)
- 传入两个及以上的数组时,它们元素数量将会相同。因为回调函数会并行地处理相互对应的元素。 如果几个数组的元素数量不一致:空元素会扩展短那个数组,直到长度和最长的数组一样。
- 此函数有个有趣的用法:传入 NULL 作为回调函数的名称,将创建多维数组(一个数组,内部包含数组。)
<?php
$a = array(1, 2, 3, 4, 5);
$b = array("one", "two", "three", "four", "five");
$c = array("uno", "dos", "tres", "cuatro", "cinco");
$d = array_map(null, $a, $b, $c);
print_r($d);
?>
以上例程会输出:
Array
(
[0] => Array
(
[0] => 1
[1] => one
[2] => uno
)
[1] => Array
(
[0] => 2
[1] => two
[2] => dos
)
[2] => Array
(
[0] => 3
[1] => three
[2] => tres
)
[3] => Array
(
[0] => 4
[1] => four
[2] => cuatro
)
[4] => Array
(
[0] => 5
[1] => five
[2] => cinco
)
)
如果仅传入一个数组,键(key)会保留;传入多个数组,键(key)是整型数字的序列。
<?php
$arr = array("stringkey" => "value");
function cb1($a) {
return array ($a);
}
function cb2($a, $b) {
return array ($a, $b);
}
var_dump(array_map("cb1", $arr));
var_dump(array_map("cb2", $arr, $arr));
var_dump(array_map(null, $arr));
var_dump(array_map(null, $arr, $arr));
?>
以上例程会输出:
array(1) {
["stringkey"]=>
array(1) {
[0]=>
string(5) "value"
}
}
array(1) {
[0]=>
array(2) {
[0]=>
string(5) "value"
[1]=>
string(5) "value"
}
}
array(1) {
["stringkey"]=>
string(5) "value"
}
array(1) {
[0]=>
array(2) {
[0]=>
string(5) "value"
[1]=>
string(5) "value"
}
}