gpt4 book ai didi

php - 如何在php中将数组合并为二维数组

转载 作者:行者123 更新时间:2023-11-29 12:00:58 28 4
gpt4 key购买 nike

我已经在谷歌上搜索到了这一点,但我认为我缺少一些东西来使其工作,合并后我会将其保存到 csv 文件或 mysql 数据库中。

这是示例数据:

01 2015-09-03 08:01
01 2015-09-03 11:03
01 2015-09-03 13:15
01 2015-09-03 17:12
07 2015-09-03 08:15
07 2015-09-03 17:06
01 2015-09-04 08:05
01 2015-09-04 11:03

我希望在将结果数组保存到 csv 文件之前像这样:

01 | 2015-09-03 | 08:01 | 11:03 | 13:15 | 17:12
07 | 2015-09-03 | 08:15 | 17:06
01 | 2015-09-04 | 08:05 | 11:03

根据元素的数量创建标题。我尝试了这段代码:

foreach($line as $value){
fputcsv($converted,$value,"\t");//write the new array to csv
}

最佳答案

您可以使用explode函数将字符串转换为数组:

$categories = [];

foreach($lines as $line) {
$array = explode(' ', $line);

// Then you can store your data using column 1 and 2 as a key
$key = $array[0] . $array[1];
$categories[$key][] = $array;
}

// finally, you can go through the $categories array
foreach ($categories as $category) {
$csv = [$category[0][0], $category[0][1]];
foreach ($category as $value) {
$csv[] = $value;
}
fputcsv($handle, $csv);
}

变量的命名很糟糕,但我希望你明白:)

关于php - 如何在php中将数组合并为二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32390879/

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