Format my JSON string into an
    ordered list in PHP

后端 未结 5 891
抹茶落季
抹茶落季 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:30

    What you're looking for is called recursion, which can be done by a function calling itself.

    If you solved once to list all nodes of the list in one function, you can then apply the same function for all child-lists. As then those child-lists will do the same on their children, too.

    call_user_func(function ($array, $id = 'id', $list = 'children') {
        $ul = function ($array) use (&$ul, $id, $list) {
            echo '
      ', !array_map(function ($child) use ($ul, $id, $list) { echo '
    • ', $child[$id], isset($child[$list]) && $ul($child[$list]) , '
    • '; }, $array), '
    '; }; $ul($array); }, json_decode('[{"id":3,"children":[{"id":4,"children":[{"id":5}]}]},{"id":6}, {"id":2},{"id":4}]', TRUE));

    As this example shows, the $ul function is called recursively over the list and all children. There are other solutions, but most often recursion is a simple method here to get the job done once you've wrapped your head around it.

    Demo: https://eval.in/153471 ; Output (beautified):

    • 3
      • 4
        • 5
    • 6
    • 2
    • 4

提交回复
热议问题