汇总多维数组的值,其中重复数组中的某些项

时间:2015-12-07 23:05:14

标签: php arrays

我在这里画一个空白,需要一些帮助。我有一个多维数组,我需要组合来自相同“tenant_id”项的数据,所以我最终得到一个数组,总结了“item_amounts”和任何tenant_id重复项的连接描述。

这是我的php数组...请注意前两个元素来自同一个tenant_id,我需要将它们合并为一个并将“item_amount”加在一起以获得最终总数:

/*
array(4) {
  [0]=>
  array(5) {
    ["tenant_id"]=>    string(5) "11252"
    ["payment_method_id"]=>    string(1) "4"
    ["item_amount"]=>    string(4) "1.00"
    ["description"]=>    string(4) "Rent"
    ["acctg_payment_id"]=>    int(3073)
  }
  [1]=>
  array(5) {
    ["tenant_id"]=>    string(5) "11252"
    ["payment_method_id"]=>    string(1) "4"
    ["item_amount"]=>    string(4) "1.20"
    ["description"]=>    string(12) "Security dep"
    ["acctg_payment_id"]=>    int(3074)
  }
  [2]=>
  array(5) {
    ["tenant_id"]=>    string(5) "11175"
    ["payment_method_id"]=>    string(1) "4"
    ["item_amount"]=>    string(4) "1.10"
    ["description"]=>    string(4) "Rent"
    ["acctg_payment_id"]=>    int(3075)
  }
  [3]=>
  array(5) {
    ["tenant_id"]=>    string(5) "11120"
    ["payment_method_id"]=>    string(1) "4"
    ["item_amount"]=>    string(4) "1.00"
    ["description"]=>    string(1) "r"
    ["acctg_payment_id"]=>    int(3076)
  }
}

*/  

这是我希望的最终结果,其中总结了“invoice_amount”以及相同的“tenant_id”的连接描述:

/*
    array(4) {
      [0]=>
      array(5) {
        ["tenant_id"]=>    string(5) "11252"
        ["payment_method_id"]=>    string(1) "4"
        ["item_amount"]=>    string(4) "2.20"
        ["description"]=>    string(4) "Rent,Security dep"
        ["acctg_payment_id"]=>    int(3073)
      }
      [1]=>
      array(5) {
        ["tenant_id"]=>    string(5) "11175"
        ["payment_method_id"]=>    string(1) "4"
        ["item_amount"]=>    string(4) "1.10"
        ["description"]=>    string(4) "Rent"
        ["acctg_payment_id"]=>    int(3075)
      }
      [2]=>
      array(5) {
        ["tenant_id"]=>    string(5) "11120"
        ["payment_method_id"]=>    string(1) "4"
        ["item_amount"]=>    string(4) "1.00"
        ["description"]=>    string(1) "r"
        ["acctg_payment_id"]=>    int(3076)
      }
    }

    */  

任何有关如何完成此任务的帮助将不胜感激。

感谢。

1 个答案:

答案 0 :(得分:0)

是的,不要那样做。您不仅会丢失信息,而且您留下的信息会产生误导。例如:您合并了多笔付款,但留在一个acctg_payment_id。我建议像:

[
    '11252' => [ //tenant ID
        'total_paid' => 220,
        'payments' => [
            [ /* payment 3073 */ ],
            [ /* payment 3074 */ ],
        ]
    ],
    ...
]

哪个应该输出:

$res = [];
foreach($payments as $payment) {
    $tid = $payment['tenant_id'];
    if( !isset($res[$tid]) ) {
        $res[$tid] = [
            'total_paid' => $payment['item_amount'],
            'payments' => [$payment]
        ];
    } else {
        $res[$tid]['total_paid'] += $payment['item_amount'];
        $res[$tid]['payments'][] = $payment;
    }
}