Reputation: 405
I wrote a code that allows me to read an excel file, transform it into csv and make modifications on it. I add at the end of this file 10 columns, the problem is that the name of the columns is added at once with "PICT1;PICT2; PICT3;PICT4;..." in only one column at the end of the 10. I would like each column to be called PICT1, PICT2, PICT3... How do I do this?
I would like that:
<?php
function multiSplit($string)
{
$output = array();
$cols = explode(",", $string);
foreach ($cols as $col)
{
$dashcols = explode("-", $col);
$output[] = $dashcols[0];
}
return $output;
}
//Modifications on csv file
$delimiter = $delimiterpost;
$csv_data = array();
$row = 1;
if (($handle = fopen($nomcsv, 'r')) !== FALSE) {
while (($data = fgetcsv($handle, 10000, $delimiter)) !== FALSE) {
//Add columns at the end
$data['Pictures Names'] = (!empty($data[4]) ? ($data[7] ?: '') . "_" . $data[4] . '.jpg' : '');
$data['Color-Description'] = (!empty($data[3]) ? (ltrim($data[4], '0') ?: '') . "-" . $data[3] : '');
$out = multiSplit($data[23]);
$data['PICT1'] = $out[0];
$data['PICT2'] = $out[1];
$data['PICT3'] = $out[2];
$data['PICT4'] = $out[3];
$data['PICT5'] = $out[4];
$data['PICT6'] = $out[5];
$data['PICT7'] = $out[6];
$data['PICT8'] = $out[7];
$data['PICT9'] = $out[8];
$data['PICT10'] = $out[9];
// Delete three columns
unset($data[1]);
unset($data[2]);
unset($data[3]);
//Modifications on the fourth line
if ($row == 4)
{
//All uppercase
$data = array_map('strtoupper', $data);
$data = str_replace(' *', '', $data);
$data = str_replace('/', '', $data);
//Replacement of spaces by an underscore
$data = str_replace(' ', '_', $data);
$data = str_replace('__', '_', $data);
//Replacement name by another name
$data = str_replace('STYLE_COLOR.JPG', 'PICT', $data);
$data = str_replace('COLOR-DESCRIPTION', 'COLOR_DESCRIPTION', $data);
array_filter($data, function($value) { return !is_null($value) && $value !== ''; });
for ( $i=1; $i<=10; $i++ ){
$data[] = "PICT$i";
}
}
if ($data[22])
{
$data = str_replace(',', '§- ', $data);
}
$csv_data[] = $data;
$row++;
}
fclose($handle);
}
$csv_data = array_slice($csv_data, 3); // this will remove first three elements
array_pop($csv_data);// this will remove last element from array
if (($handle = fopen($nomcsv, 'w')) !== FALSE) {
foreach ($csv_data as $data) {
fputcsv($handle, $data, $delimiter);
}
fclose($handle);
}
Upvotes: 0
Views: 59
Reputation: 94642
Replace
$data[] ='PICT1'.$delimiter.'PICT2'.$delimiter.'PICT3'.$delimiter.'PICT4'.$delimiter.'PICT5'.$delimiter.'PICT6'.$delimiter.'PICT7'.$delimiter.'PICT8'.$delimiter.'PICT9'.$delimiter.'PICT10';
With a loop that creates the additional array items
// clean out any empty titles as there appear to be some at the end of the array
array_filter($data, function($value) { return !is_null($value) && $value !== ''; });
for ( $i=1; $i<=10; $i++ ){
$data[] = "PICT$i";
}
Upvotes: 1