PHP实现在CSV现有列中间插入新列的技术求助
用PHP在CSV指定列位置插入新列的解决方案
问题背景
原始CSV文件details.csv内容:
name,phone,address john,123,abc suse,134,bca
需要在phone和address列之间插入新列,生成两种格式之一:
格式一(空值列)
name,phone,city,postcode,address john,123,"","",abc suse,134,"","",bca
格式二(默认值列,实现难度较低)
name,phone,city,postcode,address john,123,city,postcode,abc suse,134,city,postcode,bca
原代码将新列追加到了末尾,错误输出:
name,phone,address,city,postcode john,123,abc,city,postcode suse,134,bca,city,postcode
解决方法
核心是利用array_splice()函数在数组指定索引位置插入元素,而非直接追加到末尾,以此保留原有列的顺序。
实现格式二(默认值列)
修改后的代码:
<?php $filename = 'details.csv'; $the_big_array = []; if (($h = fopen($filename, "r")) !== FALSE) { while (($data = fgetcsv($h, 1000, ",")) !== FALSE) { // 在索引2的位置(phone列之后)插入默认列名/值 array_splice($data, 2, 0, ['city', 'postcode']); $the_big_array[] = $data; } fclose($h); } // 格式化输出结果 echo "<pre>"; foreach ($the_big_array as $row) { echo implode(',', $row) . "\n"; } echo "</pre>"; ?>
实现格式一(空值列)
将数据行的插入值替换为空字符串,并用fputcsv保证空值的CSV规范格式:
<?php $filename = 'details.csv'; $the_big_array = []; if (($h = fopen($filename, "r")) !== FALSE) { while (($data = fgetcsv($h, 1000, ",")) !== FALSE) { // 表头插入列名,数据行插入空值 if ($data[0] === 'name') { array_splice($data, 2, 0, ['city', 'postcode']); } else { array_splice($data, 2, 0, ['', '']); } $the_big_array[] = $data; } fclose($h); } // 按CSV规范输出,空值自动包裹双引号 echo "<pre>"; foreach ($the_big_array as $row) { $tempHandle = fopen('php://memory', 'w'); fputcsv($tempHandle, $row); rewind($tempHandle); echo rtrim(fgets($tempHandle), "\n") . "\n"; fclose($tempHandle); } echo "</pre>"; ?>
关键函数说明
array_splice($array, $offset, $length, $replacement):
$offset:插入位置的索引(此处为2,对应原数组中address列的前置位置)$length:设为0表示仅插入元素,不删除原有内容$replacement:待插入的元素数组
内容的提问来源于stack exchange,提问作者Pekzz
相关产品推荐
相关产品推荐

