Recursive UL LI to PHP multi-dimensional array

痞子三分冷 提交于 2020-01-03 03:12:10

问题


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";

回答1:


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;
        }
    }



回答2:


The easiest way to accomplish this is with a recursive function, like so:

//output a multi-dimensional array as a nested UL
function toUL($array){
    //start the UL
    echo "<ul>\n";
       //loop through the array
    foreach($array as $key => $member){
        //check for value member
        if(isset($member['value']) ){
            //if value is present, echo it in an li
            echo "<li>{$member['value']}</li>\n";
        }
        else if(is_array($member)){
            //if the member is another array, start a fresh li
            echo "<li>\n";
            //and pass the member back to this function to start a new ul
            toUL($member);
            //then close the li
            echo "</li>\n";
        }
    }
    //finally close the ul
    echo "</ul>\n";
}

Pass your array to that function to have it output the way you want.

Hope that helps!

Regards, Phil,



来源:https://stackoverflow.com/questions/9016257/recursive-ul-li-to-php-multi-dimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!