简体   繁体   中英

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?

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.

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 ) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM