I need to format a flat array into a multidimensional array following client's template. Here is my flat array :
$client = array(
'LastName' => 'DUPOND',
'FirstName' => 'JEAN',
'Email' => 'jdupond@free.fr',
'Address1' => '126 QUAI BACALAN',
'ZipCode' => '33160',
'City' => 'BORDEAUX',
'Country' => 'FR'
);
And here is my client's template :
$Template = array(
'Header' => array(
'Context' => array(
'LastName' => '',
'FirstName' => ''
),
'Localization' => array(
'ZipCode' => '',
'City' => '',
'Country' => '',
),
'Address1' => '',
),
'Options' => array(
'Email' => '',
),
);
So in the end i need to have a array that looks like :
$Template = array(
'Header' => array(
'Context' => array(
'LastName' => 'DUPOND',
'FirstName' => 'JEAN'
),
'Localization' => array(
'ZipCode' => '33160',
'City' => 'BORDEAUX',
'Country' => 'FR',
),
'Address1' => '126 QUAI BACALAN',
),
'Options' => array(
'Email' => 'jdupond@free.fr',
));
But it must work with any kind of template. It should work even if tomorrow clients decide to change template structure.
So from a day to another, the template can suddently become :
$Template = array(
'Header' => array(
'LastName' => '',
'FirstName' => '',
'Localization' => array(
'ZipCode' => '',
'Deeper' => array(
'EvenDeeper' => array(
'Deepest' => array(
'City' => '',
'Country' => ''
)
)
)
)
),
'Options' => array(
'Email' => '',
'Address1' => ''
));
and the function will still work !
function fillTemplate(&$template, $client) {
foreach ($template as $key => &$value) {
if (is_array($value)) {
fillTemplate($value, $client);
} elseif (isset($client[$key])) {
$value = $client[$key];
}
}
}
$result = $Template; // Make copy of template
fillTemplate($result, $client);
This walks the template recursively. When it reaches a leaf node, it replaces the value with the corresponding value from $client
. It uses reference variables as the argument and in foreach
so that the changes are made directly to the template. To preserve the original template, I make a copy of it before calling fillTemplate
.