迭代数组并替换模板中的数据

发布于 2024-12-10 08:17:02 字数 1060 浏览 0 评论 0原文

我有一个带有“标签”的 XML 文档,这些“标签”根据数组中的数据进行替换。标签有两种类型,一种是定义集合的父标签,另一种是简单地用值替换的标签。以下是用于构建和填充模板的数据示例:

$array  = array(
 'name'     => 'name',
 'city' =>  'city',
 'addresses'    =>  array(
    array(
     'street'   => '123',
     'city' =>  'main'
    ),
    array(
     'street'   => '123',
     'city' =>  'main'
     'phone'    =>  array(
        array(  
        'home'  =>  '123456',                                                                 'work'    =>  '1234567'
        )

以下是示例模板:

        <name>%name%</name>
        <city>%city%</city>
        %%addresses%%
            <street>%street%</street>
            <city>%city%</city>
            %%phone%%
                <home>%%home%%</home>
                <work>%%work%%</work>
            %%/phone%%
        %%/addresses%%

数组的键值与模板内的标签相匹配。如果键本身是一个数组,那么它将循环该键的标记 (%%) 中包含的数据。

我尝试过执行递归函数,但它似乎只能深入一层。

有人有什么建议吗?谢谢你!

I have an XML document with "tags" that are replaced based on data within an array. There are two types of tags, one is a parent tag to define a set, another is simply a tag that is replaced by a value. Here's an example of the data used to build and fill in the template:

$array  = array(
 'name'     => 'name',
 'city' =>  'city',
 'addresses'    =>  array(
    array(
     'street'   => '123',
     'city' =>  'main'
    ),
    array(
     'street'   => '123',
     'city' =>  'main'
     'phone'    =>  array(
        array(  
        'home'  =>  '123456',                                                                 'work'    =>  '1234567'
        )

Here is an example template:

        <name>%name%</name>
        <city>%city%</city>
        %%addresses%%
            <street>%street%</street>
            <city>%city%</city>
            %%phone%%
                <home>%%home%%</home>
                <work>%%work%%</work>
            %%/phone%%
        %%/addresses%%

The key values of the array, match the tags within the template. If the key is an array itself, then it loops through the data contained within that key's tag (%%).

I've tried doing a recursive function but it only seems to work one level deep.

Does anyone have any suggestions? Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

内心激荡 2024-12-17 08:17:02

我建议您使用“正常工作”的现有简单模板语言tm,例如 Mustache(还有很多其他的)。我知道 Mustache 支持数组循环,使用它,完成工作,易于集成。适用于多种语言。

I suggest you use an existing simple template language that "just works"tm, like Mustache (there are plenty much others). I know that Mustache supports looping over arrays, used it, does the job, easy to integrate. Available for many languages.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文