PHP-如何对具有重复元素值的数组元素求和[重复]

o8x7eapl  于 2023-04-19  发布在  PHP
关注(0)|答案(5)|浏览(153)

此问题已在此处有答案

Group 2d array's row data by one column and sum another column within each group to produce a reduced 2d array(3个答案)
6个月前关闭。
我有一个多数组,其中有一些重复的值是相同的名称(名称是一个元素)
我想对每个同名数组的数量求和,然后取消设置第二个数组

示例:

<?php 
 $Array=array(
  0=>array("name"=>"X","QTY"=>500),
  1=>array("name"=>"y","QTY"=>250),
  2=>array("name"=>"X","QTY"=>250)
 );
?>

现在我想对重复的值求和,如下所示。

结果:

<?php 
 $Array=array(
  0=>array("name"=>"X","QTY"=>750),
  1=>array("name"=>"y","QTY"=>250)
 );
?>

已更新

我发现这个函数在数组中搜索,foreach和另一个循环也不起作用

<?php
function search($array, $key, $value)
{
    $results = array();

    if (is_array($array)) {
        if (isset($array[$key]) && $array[$key] == $value) {
            $results[] = $array;
        }

        foreach ($array as $subarray) {
            $results = array_merge($results, search($subarray, $key, $value));
        }
    }

    return $results;
}
?>
gwo2fgha

gwo2fgha1#

试试这个最简单的,希望对你有帮助。
Try this code snippet here

$result=array();
foreach ($Array as $value)
{
    if(isset($result[$value["name"]]))
    {
        $result[$value["name"]]["QTY"]+=$value["QTY"];
    }
    else
    {
        $result[$value["name"]]=$value;
    }
}
print_r(array_values($result));
kq4fsx7k

kq4fsx7k2#

这个问题是array_reduce()的一个典型用法:

$Array = array(
    0 => array('name' => 'X', 'QTY' => 500),
    1 => array('name' => 'y', 'QTY' => 250),
    2 => array('name' => 'X', 'QTY' => 250),
);

// array_values() gets rid of the keys of the array produced by array_reduce()
// they were needed by the callback to easily identify the items in the array during processing
$Array = array_values(array_reduce(
    $Array,
    function (array $a, array $v) {
        $k = $v['name'];
        // Check if another entry having the same name was already processed
        // Keep them in the accumulator indexed by name
        if (! array_key_exists($k, $a)) {
            $a[$k] = $v;        // This is the first entry with this name
        } else {
            // Not the first one; update the quantity
            $a[$k]['QTY'] += $v['QTY'];
        }
        return $a;              // return the partial accumulator
    },
    array()                     // start with an empty array as accumulator
));
oalqel3c

oalqel3c3#

<?php

$Array=array(
0=>array("name"=>"X","QTY"=>500),
1=>array("name"=>"y","QTY"=>250),
2=>array("name"=>"X","QTY"=>250)
);

$result = array();

$names = array_column($Array, 'name');
$QTYs  = array_column($Array, 'QTY');

$unique_names = array_unique($names);

foreach ($unique_names as $name){
    $this_keys = array_keys($names, $name);
    $qty = array_sum(array_intersect_key($QTYs, array_combine($this_keys, $this_keys)));
    $result[] = array("name"=>$name,"QTY"=>$qty);
}

var_export($result);

array (
  0 => 
  array (
    'name' => 'X',
    'QTY' => 750,
  ),
  1 => 
  array (
    'name' => 'y',
    'QTY' => 250,
  ),
)
g6baxovj

g6baxovj4#

试试这个,检查**live demo**。

<?php

$Array=array(
0=>array("name"=>"X","QTY"=>500),
1=>array("name"=>"y","QTY"=>250),
2=>array("name"=>"X","QTY"=>250)
);
$keys = array_column($Array, 'name');
$QTYs = array_column($Array, 'QTY');
$result = [];
foreach($keys as $k => $v)
{
  $result[$v] += $QTYs[$k];
}
print_r($result);
bvjveswy

bvjveswy5#

您可以通过创建一个以name为键的数组,然后迭代所有值并将它们相加来实现这一点,结果如下:

function sum_same($array) {

    $keyArray = [];

    foreach ($array as $entry) {
        $name = $entry["name"];
        if(isset($keyArray[$name])) {
            $keyArray[$name] += $entry["QTY"];
        } else {
            $keyArray[$name] = $entry["QTY"];
        }
    }

    // Convert the keyArray to the old format.
    $resultArray = [];
    foreach ($keyArray as $key => $value) {
        $resultArray[] = ["name" => $key, "QTY" => $value];
    }

    return $resultArray;
}

Try the code here

如果你想改变旧的数组,可以使用这样的函数:

$myArray = sum_same($myArray);

旧阵列将被新阵列覆盖。

相关问题