PHP中的新数组搜索SUM


NEW Array Search SUM in PHP

我有一个类似的数组结构

$a = array("100","200","350"); 
$b = 400; // Is not a array is the finding value;

我想从数组中找到400和,这意味着400是一个值,是100+200+100(350-100)的和,那么返回的数组将是

$z = array("0","0","250");

这可能吗?

类似的东西?

$a = array("100","200","350"); 
$b = 400; // Is not a array is the finding value;
$left = $b;
$new_array = [];
for($i=0;$i<count($a);$i++)
{
    $new_value[] = max($a[$i]-$left, 0);
    $left = max($left - $a[$i], 0);
}
var_dump($new_value);

http://3v4l.org/d87rs

array_walk可能是一个不错的选择。使用引用,这样您就不必使用额外的内存。如果你有更大的数据,情况会更好。

<?php
//init
$a = array("100","200","350");
$b = 400; 
//walk the array. Pass by reference.
array_walk($a, function(&$item) use (&$b){
    $tmpItem = $item;
    $item = (($b-$item)>0)?0:$item-$b;
    $b-=$tmpItem;
});
//debug
print_r($a);

?>

输出:

Array
(
    [0] => 0
    [1] => 0
    [2] => 250
)

虽然array_walk()似乎是完成此任务的最佳工具,但我更喜欢不修改原始数组,而是生成一个新数组。

对于这种方法,array_reduce()是一种方法:

$a = array("100","200","350");
$b = 400;
$z = array_reduce(
    $a,                               // process $a
    function(array $carry, $item) use (& $b) {
        // Cannot subtract from $item more than its value
        $sub = min($item, $b);
        // Subtract from $item and put it into the result array
        $item   -= $sub;
        $carry[] = $item;
        // Update the remainder
        $b -= $sub;
        // Return the partial result
        return $carry;
    },
    array()                           // start with an empty list
);

代码运行后,$z包含所需的值列表,$b包含剩余值。如果$b大于0,则$z中的所有值都是0,并且$b包含$barray_sum($a)之间的差。如果$b0,则$a中的值大到足以覆盖它,并且$z中返回的值是余数。