gpt4 book ai didi

php - 如何使用 php 将两个 csv/制表符分隔成一个 csv?

转载 作者:行者123 更新时间:2023-12-02 17:59:59 25 4
gpt4 key购买 nike

我有两个文件,一个是制表符分隔的,一个是逗号分隔的 csv,它们都已上传,我需要将它们组合成一个已排序的 csv...这是到目前为止我的代码

$txt = glob('files/*.txt*');
$csv = glob('files/*.csv*');
$test = array();
if (($handle = fopen($csv[0], "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
$test[$c][] = $data[$c];
}
}
fclose($handle);
}

if (($handle = fopen($txt[0], "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
$test[$c][] = $data[$c];
}
}
fclose($handle);
}

测试数组具有两者的完整数组,但我首先遇到了一些问题 $test 数组是这样的

[0] => Array
(
[0] => Edit
[1] => y
[2] => y
[3] => y
[4] => y
[5] => y
[6] => y
[7] => y
[8] => y
[9] => y
[1] => Array
(
[0] => Event
[1] => Carolina Panthers PSL
[2] => Florida
[3] => Carolina Panthers PSL
[4] => Apple
[5] => Carolina Panthers PSL
[6] => Carolina Panthers PSL
[7] => Carolina Panthers PSL
[8] => Carolina Panthers PSL
[9] => Carolina Panthers PSL
[10] => Carolina Panthers PSL
[2] => Array
(
[0] => Venue
[1] => Bank of America Stadium
[2] => Washington Mutual
[3] => Bank of America Stadium
[4] => Apple Inc
[5] => Bank of America Stadium
[6] => Bank of America Stadium
[7] => Bank of America Stadium
[8] => Bank of America Stadium
[9] => Bank of America Stadium
[10] => Bank of America Stadium
[11] => Bank of America Stadium
[12] => Bank of America Stadium

我如何创建一个包含所有内容的新 csv,但我需要按事件名称排序,并且测试数组的这种格式似乎不对......任何想法我做错了什么......

最佳答案

假设列名位于文件的第一行,这应该可以工作:

$txt = glob('files/*.txt*');
$csv = glob('files/*.csv*');
$test = array();
$headers = array();
if (($handle = fopen($csv[0], "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
if (empty($headers)) {
for ($c=0; $c < $num; $c++) {
$headers[$c] = $data[$c];
}
}
else {
$line = array();
for ($c = 0; $c < $num; $c++) {
$line[$headers[$c]] = $data[$c];
}
$test[] = $line;
}
}
}

if (($handle = fopen($csv[0], "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$line = array();
for ($c = 0; $c < $num; $c++) {
$line[$headers[$c]] = $data[$c];
}
$test[] = $line;
}
}

这应该给你一个像这样的数组

[0] => Array
(
[Edit] => y
[Event] => Carolina Panthers PSL
[Venue] => Bank of America Stadium,
...
[1] => Array
(

[Edit] => y
[Event] => Florida
[Venue] => Washington Mutual ,
...

然后你可以使用usort在数组上通过 Event 键和自定义回调对其进行排序。请参阅该函数的文档页面以获取大量示例,或者尝试以下操作:

function my_sort($a, $b) {
return strcmp($a['Event'], $b['Event']);
}
usort($test, 'my_sort');

关于php - 如何使用 php 将两个 csv/制表符分隔成一个 csv?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8171703/

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