如何使用 PHP 轻松地将数组中的每个项目相乘?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2660152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:14:42  来源:igfitidea点击:

How can I multiply each item in an array easily with PHP?

phparrays

提问by Henryz

I have an array called $times. It is a list of small numbers (15,14,11,9,3,2). These will be user submitted and are supposed to be minutes. As PHP time works on seconds, I would like to multiply each element of my array by 60.

我有一个名为$times. 它是一个小数字列表 ( 15,14,11,9,3,2)。这些将是用户提交的,应该是几分钟。由于 PHP 时间以秒为单位,我想将数组的每个元素乘以 60。

I've been playing around with array_walkand array_mapbut I can't get those working.

我一直在玩array_walkarray_map但我无法让那些工作。

采纳答案by dkinzer

Just iterateover the array with the foreachstatement and multiply:

只需使用语句遍历数组foreach并乘以:

foreach ($times as $value) {

  $new_times[] = $value * 60;

}

回答by Gordon

You can use array_map:

您可以使用array_map

array_map() returns an array containing all the elements of arr1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map()

array_map() 将回调函数应用于每个元素后,返回一个包含 arr1 的所有元素的数组。回调函数接受的参数数量应与传递给 array_map() 的数组数量相匹配

Examples with lambda functions for callbacks:

用于回调的 lambda 函数示例:

array_map(function($el) { return $el * 60; }, $input);

Same for PHP < 5.3

PHP < 5.3 相同

array_map(create_function('$el', 'return $el * 60;'), $input);

Or with bcmulfor callback

bcmul用于回调

array_map('bcmul', $input, array_fill(0, count($input), 60));

But there is nothing wrong with just using foreachfor this as well.

但是,仅用于此也没有错foreach

回答by lamas

You may want to use foreach for simplicity in your case:

在您的情况下,为了简单起见,您可能希望使用 foreach:

foreach( $times as &$val ){ $val *= 60; }

I assume that the values of your array are the ones you want to multiply, not the keys. As the above solution uses references, it will also alter your original array - but as you were aiming at array_mapbefore, I think that you want that.

我假设你的数组的值是你想要相乘的值,而不是键。由于上述解决方案使用引用,它也会改变您的原始数组 - 但正如您array_map之前的目标,我认为您想要那样。

The solution above is probably easier to understand and most likely faster than using array_map which (obviously) has to call a function for each element. I'd use array_map only for more complicated things such as advanced sorting algorithms and so on, but definitely not for something as trivial as this.

上面的解决方案可能更容易理解,而且很可能比使用 array_map 更快,后者(显然)必须为每个元素调用一个函数。我只会将 array_map 用于更复杂的事情,例如高级排序算法等,但绝对不会用于像这样微不足道的事情。

回答by maraspin

I'd personally second the suggestion from Gordon to just use a lambda (or created) function and either do:

我个人赞同 Gordon 的建议,即只使用 lambda(或创建的)函数,然后执行以下操作:

array_map(function($el) { return $el * 60; }, $input_array);

(PHP >= 5.3) or

(PHP >= 5.3) 或

array_map(create_function('$el', 'return $el * 60;'), $input_array);

(PHP < 5.3)

(PHP < 5.3)

Definitely I see no reasons for duplicating the array (can become cumbersome if lot of values are involved); also, pay attention that using foreach (which I second can be handy) can also be dangerous if you're not working with it carefully ...and then maintenance can become daunting anyways (because you have to remember to deal with it every time you work on that code). If you have no reasons for optimizing at this stage (IE your application has not problems of speed), don't do it now and don't worry about using array_map. You can think about ease of maintenance now and optimize later, in case you really need to.

当然,我认为没有理由复制数组(如果涉及很多值,可能会变得很麻烦);另外,请注意,如果您不小心使用 foreach(我认为它很方便)也可能很危险……然后无论如何维护都会变得令人生畏(因为您必须记住每次都处理它你在那个代码上工作)。如果你在这个阶段没有理由优化(即你的应用程序没有速度问题),现在不要做,不要担心使用array_map。您现在可以考虑易于维护并稍后进行优化,以防万一。

In fact, if you go by reference and then you use foreach again, you might step into unexpected results (see example below...)

事实上,如果你通过引用然后再次使用 foreach,你可能会进入意想不到的结果(见下面的例子......)

$a=array('1','2','3');

foreach ($a as &$v) {
        $v *= 60;
}
print_r($a);
foreach ($a as $v);
print_r($a);

Output is:

输出是:

Array ( [0] => 60 [1] => 120 [2] => 180 )

数组( [0] => 60 [1] => 120 [2] => 180)

Array ( [0] => 60 [1] => 120 [2] => 120 )

数组( [0] => 60 [1] => 120 [2] => 120)

Probably not what you expect on the second cycle. This is why I usually avoid the foreach & byref combo when I can.

可能不是您对第二个周期的期望。这就是为什么我通常会尽可能避免使用 foreach 和 byref 组合的原因。

回答by Nuruzzaman Milon

from PHP 5.1 there is function called array_product(). You can use it.

从 PHP 5.1 开始,有一个名为array_product(). 你可以使用它。

$mul = array_product([1, 2, 3]);
echo $mul;  // 6

http://php.net/manual/en/function.array-product.php

http://php.net/manual/en/function.array-product.php

回答by Sergey Onishchenko

array_walk($myArray, function(&$v) {$v *= 60;});