将交叉键和值组合在2个数组中

时间:2015-10-07 18:03:38

标签: php arrays merge

我正在浏览php.net上的所有数组函数,无法解决这个问题。

基本上我想采用这两个数组:

Array
(
[0] => stdClass Object
    (
        [month] => October
        [year] => 2015
        [credit] => 1000.00
    )

[1] => stdClass Object
    (
        [month] => September
        [year] => 2015
        [credit] => 200.00
    )
)

Array
(

[0] => stdClass Object
    (
        [month] => October
        [year] => 2015
        [debit] => 2000.00
    )

[1] => stdClass Object
    (
        [month] => August
        [year] => 2015
        [debit] => 50.00
    )
)

...并使输出看起来像这样:

Array
(

[0] => stdClass Object
    (
        [month] => October
        [year] => 2015
        [credit] => 1000.00
        [debit] => 2000.00
    )

[1] => stdClass Object
    (
        [month] => September
        [year] => 2015
        [credit] => 200.00
        [debit] => 0
    )

[2] => stdClass Object
    (
        [month] => August
        [year] => 2015
        [credit] => 0
        [debit] => 50.00
    )
)

我希望合并“month”和“year”并合并其他键,如果键不存在则使用默认值。有什么指导吗?

1 个答案:

答案 0 :(得分:2)

假设$debits$credits是您问题中显示的数组,我会这样做:

首先循环学分,将它们插入新的"组合"数组并随时添加借记的默认值。

foreach ($credits as $credit) {
    $credit->debit = 0.00;   // provide a default value for debit
    $combined[$credit->year . $credit->month] = $credit;
}

然后循环借记。由于条目已经存在来自学分的可能性,因此需要对此进行检查。此部分应更新从信用中插入的现有值,或者如果没有现有值,则插入新值。

foreach ($debits as $debit) {
    if (isset($combined[$debit->year . $debit->month])) {
        // update the debit if the entry already exists
        $combined[$debit->year . $debit->month]->debit = $debit->debit;
    } else {
        // otherwise create a new entry with a default value for credit
        $debit->credit = 0.00;
        $combined[$debit->year . $debit->month] = $debit;
    }
}

// If you need the results to be numerically indexed, you can use array_values
$numerically_indexed = array_values($combined);