I'm working with an input array, which is 3 levels deep, and creating error message strings accordingly in a separate output array. Below is the code.
$e['invalid']['key'][] = 'a123';
$e['invalid']['key'][] = 'a456';
$e['invalid']['color'][] = 'red';
$e['missing']['key'][] = 'b72';
$e['missing']['color'][] = 'blue';
$e['missing']['color'][] = 'green';
echo '<pre>' . print_r($e, 1) . '</pre>';
function generateErrorMessages($e)
{
$errors;
foreach ($e as $type => $array)
{
foreach ($array as $key => $values)
{
foreach ($values as $v)
{
switch($type)
{
case 'invalid':
$errors[$type][$key][] = $v . ' is not a valid ' . $key;
break;
case 'missing':
$errors[$type][$key][] = $v . ' is a required ' . $key . ' - other functions have dependencies on it';
break;
default:
// do nothing
}
}
}
}
return $errors;
}
$msgs = generateErrorMessages($e);
echo '<pre>' . print_r($msgs, 1) . '</pre>';
While this achieves the desired outcome, the nested foreach
loops in the generateErrorMessages()
method seem onerous and difficult to read. Is there a more concise way to generate the error messages?