Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fagci/5c189856f00f4e3c4329858db19b5841 to your computer and use it in GitHub Desktop.
Save fagci/5c189856f00f4e3c4329858db19b5841 to your computer and use it in GitHub Desktop.
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