简体   繁体   English

如何让 array_walk 与 PHP 内置函数一起工作?

[英]How to get array_walk working with PHP built in functions?

I just want to use array_walk() with ceil() to round all the elements within an array.我只想使用array_walk()ceil()来舍入数组中的所有元素。 But it doesn't work.但它不起作用。

The code:编码:

$numbs = array(3, 5.5, -10.5); 
array_walk($numbs, "ceil"); 
print_r($numbs);  

output should be: 3,6,-10输出应为:3,6,-10

The error message:错误信息:

Warning: ceil() expects exactly 1 parameter, 2 given on line 2警告:ceil() 需要 1 个参数,2 个在第 2 行给出

output is: 3,5.5,-10.5 (Same as before using ceil())输出为:3,5.5,-10.5 (与之前使用 ceil() 相同)

I also tried with round() .我也尝试过round()

Use array_map instead.请改用array_map

$numbs = array(3, 5.5, -10.5);
$numbs = array_map("ceil", $numbs);
print_r($numbs);

array_walk actually passes 2 parameters to the callback, and some built-in functions don't like being called with too many parameters (there's a note about this on the docs page for array_walk ). array_walk实际上向回调传递了 2 个参数,并且一些内置函数不喜欢使用太多参数调用(在array_walk的文档页面上有关于此的说明)。 This is just a Warning though, it's not an error.虽然这只是一个警告,但它不是错误。

array_walk also requires that the first parameter of the callback be a reference if you want it to modify the array.如果您希望它修改数组, array_walk还要求回调的第一个参数是引用 So, ceil() was still being called for each element, but since it didn't take the value as a reference, it didn't update the array.因此,仍然为每个元素调用ceil() ,但由于它没有将值作为引用,因此它没有更新数组。

array_map is better for this situation. array_map更适合这种情况。

I had the same problem with another PHP function.我在另一个 PHP 函数中遇到了同样的问题。 You can create "your own ceil function".您可以创建“您自己的 ceil 函数”。 In that case it is very easy to solve:在这种情况下,很容易解决:

function myCeil(&$list){  
    $list =  ceil($list);  
}  

$numbs = [3, 5.5, -10.5];  
array_walk($numbs, "myCeil"); 

// $numbs output
Array
(
    [0] => 3
    [1] => 6
    [2] => -10
)

That is because array_walk needs function which first parameter is a reference &那是因为array_walk需要第一个参数是引用的函数&

function myCeil(&$value){
    $value = ceil($value);
}

$numbs = array(3, 5.5, -10.5); 
array_walk($numbs, "myCeil"); 
print_r($numbs); 

The reason it doesn't work is because ceil($param) expects only one parameter instead of two.它不起作用的原因是因为ceil($param)只需要一个参数而不是两个。

What you can do:你可以做什么:

$numbs = array(3, 5.5, -10.5); 
array_walk($numbs, function($item) {
    echo ceil($item);
}); 

If you want to save these values then go ahead and use array_map which returns an array.如果要保存这些值,请继续使用返回数组的array_map

UPDATE更新

I suggest to read this answer on stackoverflow which explains very well the differences between array_map , array_walk , and array_filter我建议在 stackoverflow 上阅读这个答案,它很好地解释了array_maparray_walkarray_filter之间的差异

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM