Skip to content
← Back to Functions
Code

Lookup Cache Builder

Loads small lookup tables into keyed arrays for fast repeated reads.

Function signature

ogBuildLookupCache(rows = array(), key_field = 'id', value_fields = array())

Categories

  • Maintenance and Cron

Parameters

rowsSource records.key_fieldField used as the lookup key.value_fieldsOptional fields to keep in each lookup value.

Return value

Public-safe status string returned by the function.

  • success
  • message
  • data

Compatibility

Existing function name, slug, path, and call order preserved; advertised metadata corrected to the actual source behavior.

Minimum PHP version: 7.4

Security notes

Use caller-owned allowlists and procedural mysqli prepared execution where SQL plans are returned; validate file paths, MIME policies, and permissions before file or download workflows.

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.
 */

/**
 * Builds a keyed lookup array from database rows or other records.
 *
 * @param array $rows Source records.
 * @param string $key_field Field used as the lookup key.
 * @param array $value_fields Optional fields to keep in each lookup value.
 * @return array Lookup cache result.
 */
function ogBuildLookupCache($rows = array(), $key_field = 'id', $value_fields = array()) {
	$result = array(
		'success' => false,
		'message' => '',
		'data' => array()
	);

	if (!is_array($rows)) {
		$result['message'] = 'Rows must be supplied as an array.';
		return $result;
	}

	$key_field = trim((string)$key_field);
	if (empty($key_field)) {
		$result['message'] = 'Key field is required.';
		return $result;
	}

	$lookup = array();
	$duplicates = array();
	foreach ($rows as $row) {
		if (!is_array($row) || !array_key_exists($key_field, $row)) {
			continue;
		}
		$key = (string)$row[$key_field];
		if (array_key_exists($key, $lookup)) {
			$duplicates[] = $key;
		}

		if (empty($value_fields)) {
			$lookup[$key] = $row;
		} else {
			$value = array();
			foreach ($value_fields as $field) {
				$field = (string)$field;
				if (array_key_exists($field, $row)) {
					$value[$field] = $row[$field];
				}
			}
			$lookup[$key] = $value;
		}
	}

	$result['success'] = true;
	$result['message'] = 'Lookup cache built.';
	$result['data'] = array(
		'lookup' => $lookup,
		'count' => count($lookup),
		'duplicates' => $duplicates
	);

	return $result;
}