Есть работающий парсер, который переводит текстовый файл в csv. Исходный текстовый файл имеет вот такой формат:
21 июн 15:28 Зак: 9 #1 Случайный текст
(Гот. фигня) Карандаш 1
(Гот. мигня) Майка 2
(Гот. фигня) Бумага 1
(Гот. Кухня) Тетрадь 4
(Гот. фигня) Карандаш 1
(Гот. мигня) Ластик x1
(Гот. фигня) Твердый x1
(Гот. фигня) Красный x1
(Гот. мигня) Телефон 1
(Гот. фигня) Симбиан x1
Этот файл пропускаю через вот этот скрипт:
<?php
$data = trim(file_get_contents('input.txt'));
$all_lines = preg_split("/\r?\n/", $data);
$date_id_line = array_shift($all_lines);
if(!preg_match('/^\d+\s[а-яА-Яёю]+\s(?<time>\d+:\d+)\sЗак:\s(?<id>\d+).*/', $date_id_line, $matches)) {
trigger_error('Failed to match ID and timestamp', E_USER_ERROR);
}
$output_data = array(
'info' => array(
'id' => $matches['id'],
'time' => $matches['time']
),
'data' => array()
);
$all_text_headers = array_values(preg_grep('/^\s*\(/', $all_lines));
// The first "Text header" is a parent.
// Count the number of leading whitespaces to determine other parents
preg_match('/^\x20*/', $all_text_headers[0], $leading_space_matches);
$leading_spaces = $leading_space_matches[0];
$num_leading_spaces = strlen($leading_spaces);
$parent_lead = str_repeat(' ', $num_leading_spaces) . '(';
$parent = NULL;
foreach($all_text_headers as $index => $header_line) {
list($lead, $item_value) = explode(') ', $header_line);
list($topic, $topic_count) = array_map('trim',
preg_split('/\s{2,}/', $item_value, -1, PREG_SPLIT_NO_EMPTY)
);
$topic_count = preg_replace('/\D/', '', $topic_count);
if($is_parent = ($parent === NULL || strpos($lead, $parent_lead) === 0)) {
$parent = $topic;
}
if($is_parent) {
$output_data['data'][$parent] = array(
'count' => $topic_count,
'values' => array(),
);
} else {
$output_data['data'][$parent]['values'][] = array(
'topic' => $topic,
'count' => $topic_count
);
}
}
$csv_delimiter = ';';
//output file -- result file -- CSV --
$handle = fopen('csv.txt', 'wb');
fputcsv($handle, array_values($output_data['info']), $csv_delimiter);
foreach($output_data['data'] as $parent_topic => $data) {
$child_data = array();
if($data['values']) {
foreach($data['values'] as $arr) {
$child_data[] = sprintf('%s x%d', $arr['topic'], $arr['count']);
}
}
fputcsv($handle, array(
$parent_topic,
$data['count'],
implode(', ', $child_data)
), $csv_delimiter);
}
fclose($handle);
echo "it's kinda done :-)";
?>
Получается на выходе вот такой CSV файл:
9;15:28
Карандаш;1;"Ластик x1, Твердый x1, Красный x1"
Майка;2;
Бумага;1;
Тетрадь;4;
Телефон;1;"Симбиан x1"
Всё хорошо. Только у нас всего один Карандаш. А должно быть два! Отсутствует тот, что без child. Но даже если в исходном файле было бы две строки без child, всё равно в csv файл попал бы только один.
Помогите разобраться, почему так происходит...