我需要按列对数据行进行分组并对另一列求和。
输入:
[
['quantity' => 5, 'dd' => '01-Nov-2012'],
['quantity' => 10, 'dd' => '01-Nov-2012'],
['quantity' => 3, 'dd' => '02-Nov-2012'],
['quantity' => 4, 'dd' => '03-Nov-2012'],
['quantity' => 15, 'dd' => '03-Nov-2012'],
];
期望的结果:
[
['quantity' => 15, 'dd' => '01-Nov-2012'],
['quantity' => 3, 'dd' => '02-Nov-2012'],
['quantity' => 19, 'dd' => '03-Nov-2012'],
];
只需遍历行,然后将数量加到由
dd
值索引的不同数组中。
$in = array(array()); // your input
$out = array();
foreach ($in as $row) {
if (!isset($out[$row['dd']])) {
$out[$row['dd']] = array(
'dd' => $row['dd'],
'quantity' => 0,
);
}
$out[$row['dd']]['quantity'] += $row['quantity'];
}
$out = array_values($out); // make the out array numerically indexed
var_dump($out);
Orrrrr...因为日子是独一无二的:
<?php
header('Content-type: text/plain');
$inputArray = array(
array('qty' => 5, 'dd' => '01-Nov-2012'),
array('qty' => 10, 'dd' => '01-Nov-2012'),
array('qty' => 3, 'dd' => '02-Nov-2012'),
array('qty' => 4, 'dd' => '03-Nov-2012'),
array('qty' => 15, 'dd' => '03-Nov-2012'));
$outputArray = array();
foreach ( $inputArray as $record ) {
if ( !key_exists($record['dd'], $outputArray) ) {
$outputArray[$record['dd']] = 0;
}
$outputArray[$record['dd']] += $record['qty'];
}
print_r($outputArray);
会产生:
Array
(
[01-Nov-2012] => 15
[02-Nov-2012] => 3
[03-Nov-2012] => 19
)
有许多可行的技术可以对二维数组数据进行分组和求和。
foreach()
带临时键:(Demo)
$result = [];
foreach ($array as $row) {
if (!isset($result[$row['dd']])) {
$result[$row['dd']] = $row;
} else {
$result[$row['dd']]['quantity'] += $row['quantity'];
}
}
var_export(array_values($result));
foreach()
带有引用而不是临时结果键:(Demo)
$result = [];
foreach ($array as $row) {
if (!isset($ref[$row['dd']])) {
$ref[$row['dd']] = $row;
$result[] = &$ref[$row['dd']];
} else {
$ref[$row['dd']]['quantity'] += $row['quantity'];
}
}
var_export($result);
array_reduce()
带临时键:(Demo)
var_export(
array_values(
array_reduce(
$array,
function($result, $row) {
if (!isset($result[$row['dd']])) {
$result[$row['dd']] = $row;
} else {
$result[$row['dd']]['quantity'] += $row['quantity'];
}
return $result;
}
)
)
);
array_reduce()
带有引用而不是临时键:(Demo)
var_export(
array_reduce(
$array,
function($result, $row) {
static $ref = [];
if (!isset($ref[$row['dd']])) {
$ref[$row['dd']] = $row;
$result[] = &$ref[$row['dd']];
} else {
$ref[$row['dd']]['quantity'] += $row['quantity'];
}
return $result;
}
)
);