递归UL LI至PHP多维数组 [英] Recursive UL LI to PHP multi-dimensional array

查看:107
本文介绍了递归UL LI至PHP多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试转换一个基本上采用以下格式的HTML块(每个列表项应在一行上,因此,如果您明白我的意思,则不应有任何包含<ul><li>的行):

I'm trying to convert an HTML block which is basically in the following form (each list item should be on one line, so there shouldn't be any lines containing <ul><li> if you see what I mean):

<ul>
<li>Item 1</li>
<li>
<ul>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</li>
<li>Item 4</li>
</ul>

但是可能有几层深.我基本上想将其转换为一个多维数组,其中的内容是值(实际的内容更为详细,但是我应该能够处理这些细节).输出数组几乎如下所示:

But it could be several layers deep. I basically want to convert it to a multidimensional array, where the contents are the value (the actual contents are a bit more detailed, but I should be able to process these details). Where the output array is pretty much like the below:

$array[0]['value'] = "item 1";
$array[1][0]['value'] = "item 2";
$array[1][1]['value'] = "item 3";
$array[2]['value'] = "item 4";

推荐答案

这是答案,如果以后有人遇到...

This is the answer if anyone comes across this later...

function ul_to_array($ul){
        if(is_string($ul)){
            if(!$ul = simplexml_load_string($ul)) {
                trigger_error("Syntax error in UL/LI structure");
                return FALSE;
            }
            return ul_to_array($ul);
        } else if(is_object($ul)){
            $output = array();
            foreach($ul->li as $li){
                $update_with = (isset($li->ul)) ? ul_to_array($li->ul) : (($li->count()) ? $li->children()->asXML() : (string) $li);
                if(is_string($update_with)){
                    if(trim($update_with) !== "" && $update_with !== null){
                        $output[] = $update_with;
                    }
                } else {
                        $output[] = $update_with;
                }
            }
            return $output;
        } else {
            return FALSE;
        }
    }

这篇关于递归UL LI至PHP多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆