<?php
/**
* Maps fields of text blocks for batch processing.
*
* @param array $textBlocks An array of text blocks, each with fields to map.
* @param array $fieldMappings An array of field mappings, defining how to extract data from the text blocks.
* @return array An array of processed text blocks, with the mapped fields.
*/
function mapTextBlocks(array $textBlocks, array $fieldMappings): array
{
$processedBlocks = [];
foreach ($textBlocks as $block) {
$processedBlock = []; // Initialize processed block
foreach ($fieldMappings as $fieldName => $mapping) {
$value = extractFieldValue($block, $mapping); // Extract field value using mapping
$processedBlock[$fieldName] = $value; // Assign to processed block
}
$processedBlocks[] = $processedBlock; // Add to results
}
return $processedBlocks;
}
/**
* Extracts a field value from a text block based on a mapping.
*
* @param array $block The text block to extract from.
* @param array $mapping The mapping for the field.
* @return mixed The extracted field value, or null if not found.
*/
function extractFieldValue(array $block, array $mapping)
{
foreach ($mapping as $selector => $path) {
try {
$value = pathToValue($block, $path);
return $value;
} catch (Exception $e) {
// Ignore if path is invalid
}
}
return null; // Field not found
}
/**
* Traverses the text block structure to extract a value.
*
* @param array $block The text block to traverse.
* @param string $path The path to the value (e.g., 'block.field1.subfield2').
* @return mixed The extracted value.
* @throws Exception If the path is invalid.
*/
function pathToValue(array $block, string $path)
{
$pathParts = explode('.', $path);
$current = $block;
foreach ($pathParts as $part) {
if (is_array($current) && isset($current[$part])) {
$current = $current[$part];
} else {
throw new Exception("Invalid path: " . $path); // Throw exception for invalid paths
}
}
return $current;
}
?>
Add your comment