我有两个数组。它们每个都由“日期”和“关闭”键组成。
示例:
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"
我该怎么做?
答案 0 :(得分:0)
我已经看到了使用date
作为数组键的常见模式。这将设置数据集共有的索引,以便您可以按组进行分配。
$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 )