gpt4 book ai didi

PHP合并日期数组

转载 作者:行者123 更新时间:2023-12-04 07:04:50 26 4
gpt4 key购买 nike

我有两个数组,我试图根据它们的日期进行合并。这是数组的样子:

$a[0][0] = '11/15/08';
$a[0][1] = '50';
$a[1][0] = '11/20/08';
$a[1][1] = '75';
$a[2][0] = '01/04/09';
$a[2][1] = '23';
$a[3][0] = '01/09/09';
$a[3][1] = '92';


$b[0][0] = '01/04/09';
$b[0][1] = '30';
$b[1][0] = '01/05/09';
$b[1][1] = '54';
$b[2][0] = '01/08/09';
$b[2][1] = '89';
$b[3][0] = '01/09/09';
$a[3][1] = '62';

在合并结束时,我希望:
$n[0][0] = '11/15/08';
$n[0][1] = '50';
$n[0][2] = '0';
$n[1][0] = '11/20/08';
$n[1][1] = '75';
$n[1][2] = '0';
$n[2][0] = '01/04/09';
$n[2][1] = '23';
$n[2][2] = '30';
$n[3][0] = '01/05/09';
$n[3][1] = '0';
$n[3][2] = '54';
$n[4][0] = '01/08/09';
$n[4][1] = '0';
$n[4][2] = '89';
$n[4][0] = '01/09/09';
$n[4][1] = '92';
$n[4][2] = '62';

这可能吗?

最佳答案

我首先将数组排序为一个以时间戳作为键和数字数组作为其值的数组。这将很容易排序。例如:

$result = array();
foreach (array_merge($a, $b) as $item) {
$date = $item[0];
$dateParts = explode('/', $date);
$timestamp = mktime(0,0,0,$dateParts[0], $dateParts[1], $dateParts[2]);
if (!isset($result[$timestamp])) {
$result[$timestamp] = array();
}

$result[$timestamp][] = $item[1];
}

因为键是日期时间戳,我们可以很容易地按日期对数组进行排序:
ksort($result);

然后我们可以将数组转换成你想要的格式
$result2 = array();
foreach ($result as $timestamp => $item) {
$tmp = array();

$tmp[] = date('m/d/y', $timestamp);
$tmp = array_merge($tmp, $item);
$result2[] = $tmp;
}

print_r($result2);

关于PHP合并日期数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1266307/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com