0

I having an issue merging arrays. I have 3 arrays that show particular data. I need a way to search through all three arrays and if the record matches the date I need to store it in a new custom array. I have 3 arrays that need to merge them using the date The arrays are as follows.

// ARRAY 1
$transactions = array(
array(
   "date"=>"2021-03-01",
   "trans_count"=>100,
   "trans_amount"=>5300
),
array(
   "date"=>"2021-03-02",
   "trans_count"=>95,
   "trans_amount"=>5035
),
array(
   "date"=>"2021-03-03",
   "trans_count"=>105,
   "trans_amount"=>5565
)
);

// ARRAY 2
$overdrafts = array(
array(
   "date"=>"2021-03-01",
   "od_amount"=>500
),
array(
   "date"=>"2021-03-02",
   "od_amount"=>1000
),
);

// ARRAY 3
$payouts= array(
array(
   "date"=>"2021-03-02",
   "amount"=>2300
)
);

I tried to write a function but I got stuck. The end goal is to collect all records from all 3 arrays and coming up with one array. the expected result should look like this.

$merged_arr = array(

   array(
       "date"=>"2021-03-01",
       "type"=>"transactions",
       "trans_count"=>100,
       "trans_amount"=>5300
    ),
   array(
       "date"=>"2021-03-01",
       "type"=>"overdrafts",
       "od_amount"=>500,
       
    ),

   array(
       "date"=>"2021-03-02",
       "type"=>"transactions",
       "trans_count"=>95,
       "trans_amount"=>5035
    ),
   array(
       "date"=>"2021-03-02",
       "type"=>"overdrafts",
       "od_amount"=>1000
    ),
   array(
       "date"=>"2021-03-02",
       "type"=>"payout",
       "od_amount"=>2300
    ),
);

1 Answer 1

1

Not 100% sure of how to add the type for each of the different types automatically in a nice way, I'd suggest just adding the types directly on the initial arrays, or looping through each before merging them together.

As for the merging and sorting it's pretty easy and can be done with built-in functionality.

$merged_arr = array_merge($transactions, $overdrafts, $payouts);

usort($merged_arr, function ($left, $right) {
    return new DateTime($left['date']) <=> new DateTime($right['date']);
});

// Demo merged array.
print "<pre>";

var_export($merged_arr);

The sort function will work with PHP 7 and up.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.