1

Есть работающий парсер, который переводит текстовый файл в 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 файл попал бы только один.

Помогите разобраться, почему так происходит...

2
  • 1
    как будто два одинаковых ключа не могут существовать
    – Bloom
    23 июн 2019 в 15:46
  • как это исправить?
    – user278881
    23 июн 2019 в 15:47

1 ответ 1

0

Причина в том, что ключи $parent у данных, добавляемые в ассоциативный массив $output_data['data'] повторяются - происходит их перезапись и поэтому у вас результат содержит только один последний карандаш.

Решение - вместо ассоциативного массива использовать обычный и добавлять в него элементы - ассоциативные массивы, содержащие всю нужную o 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 :-)";
2
  • не работает... csv файл содержит строки, которые начинаются с 0, 1, 2, 3...
    – user278881
    23 июн 2019 в 19:45
  • @PhilippNesterov, Вот код, слегка адаптированный к песочнице. Исходные данные берутся из переменной, вместо файла, а вывод результа (csv-данных) происходит не в файл а в стандартный поток вывода. Это разве не то, что Вам нужно было?
    – Jigius
    24 июн 2019 в 1:23

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.