簡體   English   中英

取兩個單獨的數組的一部分,並將它們組合成一個

[英]Take parts of two separate arrays and combine them into one

我有兩個數組。 它們每個都由“日期”和“關閉”鍵組成。

例:

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']
    ];
}

我想將兩個數組合並為一個,將記錄的日期匹配為一個日期,然后從每個數組中獲取close值並將其用於新數組。

例:

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"

我該怎么做?

我已經看到了使用date作為數組鍵的常見模式。 這將設置數據集共有的索引,以便您可以按組進行分配。

演示: 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 ) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM