从平面数据在 PHP 中构建分层 html 标签
如何在 PHP 中使用数据构建一组分层标签?
例如,一个嵌套列表:
<div>
<ul>
<li>foo
</li>
<li>bar
<ul>
<li>sub-bar
</li>
</ul>
</li>
</ul>
</div>
这将由如下所示的平面数据构建:
nested_array = array();
nested_array[0] = array('name' => 'foo', 'depth' => 0)
nested_array[1] = array('name' => 'bar', 'depth' => 0)
nested_array[2] = array('name' => 'sub-bar', 'depth' => 1)
如果它也像示例那样具有良好的格式,那就太好了。
How do you build a hierarchical set of tags with data in PHP?
For example, a nested list:
<div>
<ul>
<li>foo
</li>
<li>bar
<ul>
<li>sub-bar
</li>
</ul>
</li>
</ul>
</div>
This would be build from flat data like this:
nested_array = array();
nested_array[0] = array('name' => 'foo', 'depth' => 0)
nested_array[1] = array('name' => 'bar', 'depth' => 0)
nested_array[2] = array('name' => 'sub-bar', 'depth' => 1)
It would be nice if it were nicely formatted like the example, too.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编辑:添加格式
正如评论中已经说过的,您的数据结构有点奇怪。 我不喜欢使用文本操作(如 OIS),而是更喜欢 DOM:
您的格式约定有点奇怪。 将最后一行替换为以下内容即可实现:
Edit: Added formatting
As already said in the comments, your data structure is somewhat strange. Instead of using text manipulation (like OIS), I prefer DOM:
Your formatting convention is kind of strange. Replace the last line with the following to achieve it:
我有一个问题,关于你的问题,这个问题对于评论字段来说太复杂了。
您想如何将属性数据放入其中? 您需要像 Whory Table™ 一样,
因为这是以编程方式准确表示 HTML 数据集所需的最小结构。
,从而消除了对“文本节点”元素的需要,这有点作弊
我通过假设如果数组(名称,属性,孩子)
有一个字符串而不是“孩子”的数组,那么它是一个隐式文本 -节点,
name == null 的节点没有标签,因此也是文本节点。
我认为你想要的是一个合适的编程 DOM 生成工具,它将一些现有的 html 解析成树,让你的生活更轻松
FWIW,上面的结构可以很容易地序列化为 html。
I have a question, regarding your question that is too elaborate for a comment field.
How do you want to fit attribute data in that? You'd need a Whory Table™ like
because that is the minimal structure required to accurately represent an HTML dataset programmatically.
I've cheated a bit by eliminating the need for "text-node" elements quite as much, by making the assumption if
array( name, attribute, children )
has a string instead of an array for 'children' then its an implicit text-node,
and that nodes with name == null are dont have tags and are thus also text nodes.
What I think you want is a proper programmatic DOM generation tool, which will parse some existing html into a tree to make your life easier
FWIW, the above structure can be serialised into html rather easily.
你的意思是像
产品
这样的东西,我知道如果子列表不以解释开头,那么那里会有一点差距。
就我个人而言,我通常并不关心 HTML 的外观,只要它在 PHP 中易于使用即可。
编辑:好的,如果你先运行它,它就会起作用......:P
You mean something like
produces
I know theres a little gap there if a sub list don't start with an explanation.
Personally I usually don't really care how the HTML looks as long as its easy to work with in PHP.
Edit: OK, it works if you run it through this first ... :P