1

可能重复:
php如何按特定值对多维数组进行分组?
php 使用多维数组按 SUM 分组

我需要一些帮助来获取数组元素数量的计数,方法是根据 php 中多维数组的日期值部分对其进行分组

这是我的原始数组

Array
(
[0] => Array
    (
        [quantity] => 5
        [dd] => 01-Nov-2012
    )

[1] => Array
    (
        [quantity] => 10
        [dd] => 01-Nov-2012
    )

[2] => Array
    (
        [quantity] => 3
        [dd] => 02-Nov-2012
    )

[3] => Array
    (
        [quantity] => 4
        [dd] => 03-Nov-2012
    )

[3] => Array
    (
        [quantity] => 15
        [dd] => 03-Nov-2012
    )
)

这是我期待的输出

Array
(
[0] => Array
    (
        [quantity] => 15
        [dd] => 01-Nov-2012
    )

[1] => Array
    (
        [quantity] => 3
        [dd] => 02-Nov-2012
    )

[2] => Array
    (
        [quantity] => 19
        [dd] => 03-Nov-2012
    )
)
4

2 回答 2

2

只需遍历行,然后将数量添加到由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);
于 2012-11-08T07:07:04.113 回答
1

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
)
于 2012-11-08T09:10:08.193 回答