php脚本,用于将csv文件读取到json,在项之前带有静态头



这是我的CSV数据

系统TransId>性别20-007440FMM
Shulename Shuleid事务日期1ttId
mzimu 01-022-12021年5月18日12
mzimu 01-022-1 20-007441 2021年5月18日 13
mzimu 01-022-1 20-007442 2021年5月19日 14

您可以在这里看到它的工作演示:https://www.tehplayground.com/400X1OR0vepmj7o6

我伪造了csv流,以展示如何将其与fgetcsv一起使用

$csv = "Shulename,Shuleid,systemTransId,transactionDate,sttId,gender
mzimu,01-022-1,20-007440,18/05/2021,12,F
mzimu,01-022-1,20-007441,18/05/2021,13,M
mzimu,01-022-1,20-007442,19/05/2021,14,M";
//$file = fopen("YOURFILE.csv","r");
$file     = fopen('data://text/plain,' . $csv,'r');
$line = 0 ;
$keys = [];
while (($data = fgetcsv($file)) !== FALSE)
{
if ($line==0) {
// set up the array
foreach ($data as $d) $keys[]=strtolower($d);

$output = array(
$keys[0] => "", 
$keys[1] => "",
"items" => array()
);
} else {
if ($line==1) {
$output[$keys[0]] = $data[0];
$output[$keys[1]] = $data[1];
}
$tmp = [];
for ($x=2; $x<count($keys); $x++) {
$tmp[$keys[$x]] = $data[$x];
}   
$output['items'][]=$tmp;
}
$line++;
}
$output = json_encode($output, JSON_PRETTY_PRINT);

die("<pre>".print_r($output,1));

根据您的评论,如果我理解正确,shulename将始终是mzimushuleid将始终是01-022-1

因此,从你写的代码开始,继续创建你想要的格式就是


if (($handle = fopen('revenue.csv', 'r')) === false) {
die('Error opening file');
}
$headers = fgetcsv($handle, 1024, ',');
$complete = array();
while ($row = fgetcsv($handle, 1024, ',')) {
$complete[] = array_combine($headers, $row);
}
fclose($handle);
// We have shulename and shuleid assigned statically
// because you said they will always be the same
$requiredFormat = ['shulename' => 'mzimu',
'shuleid' => '01-022-1'];
foreach ($complete as $item) {
## Notice the case here. The csv in the question is ucfirst and the required format is lower case
## php indexes are case sensitive
unset($item['Shulename']);
unset($item['Shuleid']);
$requiredFormat['items'][] = $item;
}
echo json_encode($requiredFormat);

最新更新