Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP function to render string path template using nested array
<?php
/**
* PHP function to render string path template using nested array.
* Renders template string like "Nested array item value: {data.some.nested.item.value}"
* @param string $template
* @param array $data
* @return string
*/
public static function renderDataTemplate(string $template, array $data): string
{
return preg_replace_callback('/{([^{}]+?)}/', static function ($v) use ($data) {
$temp = &$data;
foreach (explode('.', $v[1]) as $key) {
$temp = &$temp[$key] ?? null;
if ($temp === null) {
return null;
}
}
return $temp;
}, $template);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.