通过在PHP分组多维数组计数[复制](Count by grouping Multidimensio

2019-07-03 15:45发布

可能重复:
PHP如何组由特定值的多维数组?
使用多维阵列由SUM PHP组

我需要通过分组它基于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
    )
)

Answer 1:

只是循环槽的行中,并且在由索引的不同阵列加起来量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);


Answer 2:

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
)


文章来源: Count by grouping Multidimensional arrays in PHP [duplicate]