Format my JSON string into an
    ordered list in PHP

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

    You can use recursion to get deep inside the data. If the current value is an array then recursion again. Consider this example:

    $json_string = '[{"id":3,"children":[{"id":4,"children":[{"id":5}]}]},{"id":6},{"id":2},{"id":4}]';
    $array = json_decode($json_string, true);
    
    function build_list($array) {
        $list = '
      '; foreach($array as $key => $value) { foreach($value as $key => $index) { if(is_array($index)) { $list .= build_list($index); } else { $list .= "
    1. $index
    2. "; } } } $list .= '
    '; return $list; } echo build_list($array);

提交回复
热议问题