thejump
thejump

Reputation: 33

Combine intersecting keys and values in 2 arrays

I'm running through all of the array functions on php.net and unable to figure this out.

Essentially I want to take these two arrays:

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
    )
)

...and have the output look like this:

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
    )
)

I'm looked to merge "month" and "year" and combine the other keys, using a default value if the key doesn't exist. Any guidance?

Upvotes: 1

Views: 75

Answers (1)

Don't Panic
Don't Panic

Reputation: 41820

Assuming $debits and $credits are the arrays shown in your question, I would approach it like this:

First loop over the credits, inserting them into the new "combined" array and adding a default value for debit as you go.

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

Then loop over the debits. Since there is the possibilities that entries will already be there from credits, there needs to be a check for this. This part should update existing values inserted from credits, or insert new values if there is no existing value.

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);

Upvotes: 2

Related Questions