在其他语言中对此有很多疑问,但是我在PHP中找不到任何东西。我有这个$trades
数组,其中包含列数量,价格和时间:
$trades = array(
array(87.23, 97.14, "2018-10-04 03:53:37"),
array(376.81, 100.16, "2018-10-04 01:36:56"),
array(343.17, 97.67, "2018-10-04 01:26:17"),
array(291.31, 97.99, "2018-10-04 00:12:2"),
array(60.47, 96.42, "2018-10-03 18:08:30"),
array(353.18, 94.04, "2018-10-03 14:30:24"),
array(490.11, 99.06, "2018-10-03 11:24:48"),
array(377.52, 96.06, "2018-10-03 06:05:31"),
array(99.04, 100.71, "2018-10-03 04:19:53"),
array(339.67, 96.17, "2018-10-03 02:35:42"),
array(195.14, 94.93, "2018-10-03 02:24:55"),
array(230.45, 95.08, "2018-10-02 15:29:07")
);
我认为按day
对内部数组进行分组,并在每个组中找到第一个,最大,最小和最后一个price
值,这将为每天提供所需的打开,高,低,关闭条目。我试图分组,但出现错误。
foreach ($trades as $trade) {
$trade[2] = date('m d', strtotime($trade[2]));
}
$tradeGrouped = array();
foreach ($trades as $trade) {
$tradeGrouped[$trade[2]] = $trade;
}
我想要的是这样的
$ohlc = array(
array("10-02", 95.08, 95.08, 95.08, 95.08),
array("10-03", 100.71, 100.71, 94.04, 96.42)
array("10-04", 97.99, 100.16, 97.14, 97.14)
);
答案 0 :(得分:1)
使用$tradeGrouped[$trade[2]]
只能保留每个日期的最后一个值。
这将创建一个数组,其中每个日期都有很多交易:
$groups = [];
foreach ($trades as $trade) {
$date = date('m d', strtotime($trade[2]));
// Use this to handle dates from multiple years.
// $date = substr($trade[2], 0, 10);
if (!array_key_exists($date, $groups)) {
$groups[$date] = [];
}
$groups[$date][] = $trade;
}
这将直接创建组,而无需更改输入。