Format my JSON string into an
    ordered list in PHP

后端 未结 5 895
抹茶落季
抹茶落季 2021-01-29 14:48

I\'m working on a simple CMS for a pet project. I currently have a JSON string that contains a list of page ID\'s and Parent page ID\'s for a menu structure.

I want to n

5条回答
  •  庸人自扰
    2021-01-29 15:16

    Using a function that can recursively go through your JSON, you can get the functionality you wish. Consider the following code: (this only accounts for an attribute of id as getting listed, as your desired code shows)

    $json = '[{"id":3,"children":[{"id":4,"children":[{"id":5}]}]},{"id":6},{"id":2},{"id":4}]';
    
    function createOLList($group) {
        $output = (is_array($group)) ? "
      " : ""; foreach($group as $attr => $item) { if(is_array($item) || is_object($item)) { $output .= createOLList($item); } else { if($attr == "id") { $output .= "
    1. $item
    2. "; } } } $output .= (is_array($group)) ? "
    " : ""; return $output; } print(createOLList(json_decode($json)));

    This will produce the following HTML output.

    1. 3
      1. 4
        1. 5
    2. 6
    3. 2
    4. 4

提交回复
热议问题