Take parts of two separate arrays and combine them into one


Take parts of two separate arrays and combine them into one



I have two arrays. Each of them consist of "date" and "close" keys.



Example:


Array1 - Date: 12-Jun-18, Close: "55.6"
Array2 - Date: 12-Jun-18, Close: "1.26"

$stock_one_prices = sw::shared()->prices->getForStockID($id);
$stock_one_prices_array = array();

foreach ($stock_one_prices as $stock_one_price) {
$stock_one_prices_array = [
"date" => $stock_one_price['date'],
"close" => $stock_one_price['close']
];
}

$stock_two_prices = sw::shared()->prices->getForStockID($idtwo);
$stock_two_prices_array = array();

foreach ($stock_two_prices as $stock_two_price) {
$stock_two_prices_array = [
"date" => $stock_two_price['date'],
"close" => $stock_two_price['close']
];
}



I would like to take the two arrays and combine them into one, matching the dates of the records to make into one date, and then taking the close value from each array and using them for the new array.



Example:


Array1 - Date: 12-Jun-18, Close: "55.6"
Array2 - Date: 12-Jun-18, Close: "1.26"

Array1 - Date: 13-Jun-18, Close: "58.6"
Array2 - Date: 13-Jun-18, Close: "2.37"

New Array
----------
Date: 12-Jun-18, CloseOne: "55.6", CloseTwo: "1.26"
Date: 13-Jun-18, CloseOne: "58.6", CloseTwo: "2.37"



How can I accomplish this?




1 Answer
1



I've seen a common pattern that uses the date as an array key. This sets up an index common to your dataset so that you can do assignment by group.


date



demo: https://3v4l.org/jRQo0


$array1 = [
[
'date' => '12-Jun-18',
'close' => 55.6,
],
[
'date' => '13-Jun-18',
'close' => 58.6,
],
];

$array2 = [
[
'date' => '12-Jun-18',
'close' => 1.26,
],
[
'date' => '13-Jun-18',
'close' => 2.37,
],
];

$all = array_merge($array1, $array2);

foreach ($all as $datapoint) {
$result[$datapoint['date']] = $datapoint['close'];
}

print_r($result);


[12-Jun-18] => Array
(
[0] => 55.6
[1] => 1.26
)

[13-Jun-18] => Array
(
[0] => 58.6
[1] => 2.37
)






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

How to set up datasource with Spring for HikariCP?

Display dokan vendor name on Woocommerce single product pages