Snippets

Oleksiy Kalinichenko Converting flat string list to hierarchical array

Created by Oleksiy Kalinichenko last modified
<?php

include_once __DIR__ . '/includes/common.inc';

function getdatafromfile($file_name) {
  $csv = array_map('str_getcsv', file($file_name));
  array_walk($csv, function (&$a) use ($csv) {
    $a = (object) array_combine($csv[0], $a);
  });
  array_shift($csv);
  return $csv;
}

$rows = getdatafromfile('acs_census_table_number_lookup1.csv');

// Define maine variables to walk through flat array.
$indentation = '-';
$current_indent = 0;
$previous_indent = 0;
$tree = array();
$cursor = &$tree;
$parents = array();

// Run data row processing of flat array.
foreach ($rows as $row) {
  // Detect current indent.
  $current_indent = substr_count($row->hierarchical_labels, $indentation);

  // Root level.
  if ($current_indent == 0) {
    // We should always use `table_id` as key on the root level.
    $parents = array($row->table_id);
  }
  // Level down.
  elseif ($current_indent > $previous_indent) {
    $leaf = drupal_array_get_nested_value($tree, $parents);
    end($leaf);
    array_push($parents, key($leaf), 'child');
  }
  // Level up.
  elseif ($current_indent < $previous_indent) {
    $parents = array_slice($parents, 0, -2);
  }
  // Same level.
  elseif ($current_indent == $previous_indent) {
    // Nop
  }

  // Get items by cursor.
  $leaf = drupal_array_get_nested_value($tree, $parents);

  // Add to items a new one by cursor.
  $leaf[$row->hierarchical_labels] = array(
    'entity' => $row,
    'child' => array(),
  );

  // Update items by cursor.
  drupal_array_set_nested_value($tree, $parents, $leaf);

  // Update previous indent.
  $previous_indent = $current_indent;
}

return;

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.