A
The reason is the keys. $parent data added to the associated mass $output_data['data'] Once again, there's a census going on, so you only have one last pencil.The solution - instead of the associated mass, use the usual and add elements - associated masses containing all the information required from the parent - child.<?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;
$current_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) {
if ($current_parent) {
$output_data['data'][] = $current_parent;
}
$current_parent = array(
'parent_topic' => $parent,
'data' => array(
'count' => $topic_count,
'values' => array(),
)
);
} else {
$current_parent['data']['values'][] = array(
'topic' => $topic,
'count' => $topic_count
);
}
}
if ($current_parent) {
$output_data['data'][] = $current_parent;
}
$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 $data) {
$child_data = array();
if(!empty($data['data']['values'])) {
foreach($data['data']['values'] as $arr) {
$child_data[] = sprintf('%s x%d', $arr['topic'], $arr['count']);
}
}
fputcsv($handle, array(
$data['parent_topic'],
$data['data']['count'],
implode(', ', $child_data)
), $csv_delimiter);
}
fclose($handle);
echo "it's kinda done :-)";