array_filter()和array_map()之间的区别? [英] Difference between array_filter() and array_map()?

查看:165
本文介绍了array_filter()和array_map()之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我研究了Web中类似的主题以及堆栈溢出,但是可以清楚地认识到这一点. array_map,array_walk和array_filter之间的差异

I looked into the similar topics in web as well stack overflow, but could get this one into my head clearly. Difference between array_map, array_walk and array_filter

<?php
error_reporting(-1);

$arr = array(2.4, 2.6, 3.5);

print_r(array_map(function($a) {
    $a > 2.5;
},$arr));

print_r(array_filter($arr, function($a){
    return $a > 2.5;
}));

?>

上面的代码为我返回了一个过滤后的数组,其值> 2.5 .我可以用array_map实现array_filter的功能吗?.

The above code returns me a filtered array whose value is > 2.5. Can i achieve what an array_filter does with an array_map?.

推荐答案

所有三个, array_filter array_map foreach 循环通过 $ key => $ value 对.
在这篇文章的整个过程中,我将引用传递给上述函数的原始数组,作为 $ array ,循环中当前项目的索引,与 $ key 以及循环中当前项目的值,如 $ value .

All three, array_filter, array_map, and array_walk, use a callback function to loop through an array much in the same way foreach loops loop through an $array using $key => $value pairs.
For the duration of this post, I will be referring to the original array, passed to the above mentioned functions, as $array, the index, of the current item in the loop, as $key, and the value, of the current item in the loop, as $value.

array_filter 类似于MySQL的SELECT查询,它选择记录但不修改它们.
array_filter的回调传递给当前循环项目的 $ value 回调返回被视为布尔值.
如果 true ,则该项目包含在结果中.
如果 false ,则该项目将从结果中排除.
因此,您可以这样做:

array_filter is likened to MySQL's SELECT query which SELECTs records but doesn't modify them.
array_filter's callback is passed the $value of the current loop item and whatever the callback returns is treated as a boolean.
If true, the item is included in the results.
If false, the item is excluded from the results.
Thus you might do:

<pre><?php
$users=array('user1'=>array('logged_in'=>'Y'),'user2'=>array('logged_in'=>'N'),'user3'=>array('logged_in'=>'Y'),'user4'=>array('logged_in'=>'Y'),'user5'=>array('logged_in'=>'N'));
function signedIn($value)
{
    if($value['logged_in']=='Y')return true;
    return false;
}
$signedInUsers=array_filter($users,'signedIn');
print_r($signedInUsers);//Array ( [user1] => Array ( [logged_in] => Y ) [user3] => Array ( [logged_in] => Y ) [user4] => Array ( [logged_in] => Y ) )
?></pre>

另一方面,

array_map 接受多个数组作为参数. 如果指定了一个数组,则循环中当前项目的$ value将发送到回调. 如果使用两个或多个数组,则所有数组都必须先通过

array_map on the other hand accepts multiple arrays as arguments. If one array is specified, the $value of the current item in the loop is sent to the callback. If two or more arrays are used, all the arrays need to first be passed through array_values as mentioned in the documentation:

如果array参数包含字符串键,则返回数组 仅当仅传递了一个数组时,才会包含字符串键. 如果传递了多个参数,则返回的数组始终具有 整数键

If the array argument contains string keys then the returned array will contain string keys if and only if exactly one array is passed. If more than one argument is passed then the returned array always has integer keys

第一个数组被循环通过,其值作为第一个参数传递给回调,如果指定了第二个数组,它也将被循环通过,其值将作为第二个参数发送给回调,依此类推-on,等等.每个附加参数.
如果数组的长度不匹配,则使用最大的数组,如

The first array is looped through and its value is passed to the callback as its first parameter, and if a second array is specified it will also be looped through and its value will be sent as the 2nd parameter to the callback and so-on and so-forth for each additional parameter.
If the length of the arrays don't match, the largest array is used, as mentioned in the documentation:

通常,当使用两个或多个数组时,它们的长度应相等 因为回调函数与 相应的元素.如果数组长度不相等,则缩短 那些将用空元素扩展以匹配长度 最长.

Usually when using two or more arrays, they should be of equal length because the callback function is applied in parallel to the corresponding elements. If the arrays are of unequal length, shorter ones will be extended with empty elements to match the length of the longest.

每次调用回调时,都会收集返回值. 仅在使用一个数组时才保留键,并且array_map返回结果数组. 如果使用两个或多个数组,则键会丢失,而是返回一个由回调结果填充的新数组. array_map仅向回调函数发送当前项目的$ value而不是其$ key. 如果还需要键,则可以传递array_keys($array)作为附加参数,然后回调将同时接收$ key和$ value.
但是,当使用多个数组时,原始键将以与array_values丢弃键几乎相同的方式丢失. 如果需要保留密钥,则可以使用
array_keys 进行抓取原始数组中的键和 array_values 从结果中获取值 array_map 的结果,或仅使用

Each time the callback is called, the return value is collected. The keys are preserved only when working with one array, and array_map returns the resulting array. If working with two or more arrays, the keys are lost and instead a new array populated with the callback results is returned. array_map only sends the callback the $value of the current item not its $key. If you need the key as well, you can pass array_keys($array) as an additional argument then the callback will receive both the $key and $value.
However, when using multiple arrays, the original keys will be lost in much the same manner as array_values discards the keys. If you need the keys to be preserved, you can use array_keys to grab the keys from the original array and array_values to grab the values from the result of array_map, or just use the result of array_map directly since it is already returning the values, then combine the two using array_combine.

因此您可以这样做:

<pre><?php
$array=array('apple'=>'a','orange'=>'o');
function fn($key,$value)
{
    return $value.' is for '.$key;
}
$result=array_map('fn',array_keys($array),$array);
print_r($result);//Array ( [0] => a is for apple [1] => o is for orange )
print_r(array_combine(array_keys($array),$result));//Array ( [apple] => a is for apple [orange] => o is for orange )
?></pre>

array_walk foreach($array as $key=>$value),因为向回调发送了键和值.如果要将第3个参数直接传递给回调,则它也接受一个可选参数.
array_walk返回一个布尔值,该值指示循环是否成功完成.
(我尚未找到实际用途)
请注意,array_walk不使用回调的返回值. 由于array_walk返回一个布尔值,为了使array_walk影响某事, 您将需要引用& $ value,以便您可以修改或使用全局数组. 另外,如果您不想污染全局范围,则可以使用array_walk的可选第3个参数来传递对要写入的变量的引用.

array_walk is very similar to foreach($array as $key=>$value) in that the callback is sent both a key and a value. It also accepts an optional argument if you want to pass in a 3rd argument directly to the callback.
array_walk returns a boolean value indicating whether the loop completed successfully.
(I have yet to find a practical use for it)
Note that array_walk doesn't make use of the callback's return. Since array_walk returns a boolean value, in order for array_walk to affect something, you'll need to reference &$value so you have that which to modify or use a global array. Alternatively, if you don't want to pollute the global scope, array_walk's optional 3rd argument can be used to pass in a reference to a variable with which to write to.

因此您可以这样做:

<pre><?php
$readArray=array(1=>'January',2=>'February',3=>'March',4=>'April',5=>'May',6=>'June',7=>'July',8=>'August',9=>'September',10=>'October',11=>'November',12=>'December');
$writeArray=array();
function fn($value,$key,&$writeArray)
{
  $writeArray[$key]=substr($value,0,3);
}
array_walk($readArray,'fn',&$writeArray);
print_r($writeArray);//Array ( [1] => Jan [2] => Feb [3] => Mar [4] => Apr [5] => May [6] => Jun [7] => Jul [8] => Aug [9] => Sep [10] => Oct [11] => Nov [12] => Dec )
?></pre>

这篇关于array_filter()和array_map()之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆