Skip to content
← Back to Functions
Code

Flatten Records For Export

Converts nested records into flat export rows using configured column paths.

Function signature

ogFlattenRecordsForExport(records, column_map, default_value = '')

Categories

  • File and Upload Safety

Parameters

recordsRecords to flatten.column_mapExport column name to dot-path map.default_valueDefault value for missing or non-scalar values.

Return value

Short public-safe status message.

  • rows
  • count

Compatibility

Existing function name and call order preserved; metadata signature corrected to source.

Minimum PHP version: 7.4

Security notes

Validate request method, identity, permissions, and caller-owned allowlists before use; keep secrets and internal paths out of public output.

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Flattens nested records into export rows by configured dot paths.
 *
 * Column map format: exported column name => dot.path.inside.record.
 * Missing values use the supplied default value.
 *
 * @param array $records Records to flatten.
 * @param array $column_map Export column name to dot-path map.
 * @param string $default_value Default value for missing or non-scalar values.
 * @return array Structured result with flattened rows.
 */
function ogFlattenRecordsForExport($records, $column_map, $default_value = '') {
	$result = array(
		'success' => false,
		'message' => '',
		'data' => array()
	);

	if (!is_array($records)) {
		$result['message'] = 'Records must be an array.';
		return $result;
	}

	if (!is_array($column_map)) {
		$result['message'] = 'Column map must be an array.';
		return $result;
	}

	$rows = array();
	foreach ($records as $record) {
		if (!is_array($record)) {
			continue;
		}

		$row = array();
		foreach ($column_map as $column_name => $path) {
			$column_name = (string)$column_name;
			$parts = explode('.', (string)$path);
			$current = $record;
			$found = true;

			foreach ($parts as $part) {
				if (is_array($current) && array_key_exists($part, $current)) {
					$current = $current[$part];
				} else {
					$found = false;
					break;
				}
			}

			if (!$found || is_array($current) || is_object($current)) {
				$row[$column_name] = $default_value;
			} else {
				$row[$column_name] = (string)$current;
			}
		}
		$rows[] = $row;
	}

	$result['success'] = true;
	$result['message'] = 'Records flattened for export.';
	$result['data'] = array(
		'rows' => $rows,
		'count' => count($rows)
	);

	return $result;
}