From 6e0a397725d04e045e816c0f43fb6baef19341da Mon Sep 17 00:00:00 2001 From: Urban Müller Date: Mon, 8 Jan 2024 15:13:24 +0100 Subject: add option for allowing missing column values at end of row --- it_pipe.class | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/it_pipe.class b/it_pipe.class index fafc11f..03d9c69 100644 --- a/it_pipe.class +++ b/it_pipe.class @@ -184,6 +184,7 @@ function cols($collist, $separator = "\t") * Return contents of pipe as associative records. Column titles read from first line, separators can be \t or ; or , * @param $p['forceschema'] ignore schema in file, replace it with this comma separated column list * @param $p['fixcolnames'] replace non-identifier chars in colum names + * @param $p['allowmissingcols'] replace missing column values at end by null * @param $p['it_error'] error params * @return array of objects or empty array on format violations */ @@ -199,11 +200,12 @@ function csv($p = []) $oldlocale = setlocale(LC_CTYPE, "0"); setlocale(LC_CTYPE, 'de_CH.iso-8859-1'); # this works for utf-8 as well + $nullcols = $p['allowmissingcols'] ? array_fill(0, count($schema), null) : []; foreach ($this->lines as $line) { - if (($cols = str_getcsv($line, $splitchar, '"')) && count($schema) == count($cols)) - $records[] = (object)array_combine($schema, $cols); + if (($cols = str_getcsv($line, $splitchar, '"')) && (count($schema) == count($cols) || $nullcols)) + $records[] = (object)array_combine($schema, $cols + $nullcols); else return (array)it::error((array)$p['it_error'] + ['title' => "csv column count mismatch: " . count($schema) . " in header vs " . count($cols) . " in row", 'body' => [$schema, $cols]]); } -- cgit v1.2.3