Как я могу сгенерировать необычный формат JSON с помощью PHP

0

пожалуйста, я впервые использую fancytree, и я нашел некоторые трудности в создании результата Json для fancytree. У меня есть таблица базы данных, содержащая id, name, desc, parent_id.

Я работаю над codeigniter, это мой код:

public function my_tree(){
    $this->data['tree'] = array();
    $res = $this->crud->read('dbtree')->result_array();
//iterate on results row and create new index array of data
    foreach($res as $value){
        $this->data['tree'] = $res;
    }
$itemsByReference = array();
    // Build array of item references:
    foreach($this->data['tree'] as $key => &$item) {
       $itemsByReference[$item['id']] = &$item;
       // Children array:
       $itemsByReference[$item['id']]['children'] = array();
       // Empty data class (so that json_encode adds "data: {}" )
       $itemsByReference[$item['id']]['data'] = new StdClass();
    }

    // Set items as children of the relevant parent item.
    foreach($this->data['tree'] as $key => &$item)
       if($item['parent_id'] && isset($itemsByReference[$item['parent_id']]))
          $itemsByReference [$item['parent_id']]['children'][] = &$item;

    // Remove items that were added to parents elsewhere:
    foreach($this->data['tree'] as $key => &$item) {
       if($item['parent_id'] && isset($itemsByReference[$item['parent_id']]))
          unset($this->data['tree'][$key]);
    }
    // Encode:
    $this->data['page'] = "server_tree";
    $this->load->view('layout', $this->data);
}

Как я могу сделать эти ключи с помощью php loop:

[
{"title": "Expanded folder with children", "expanded": true, "folder": true, "children": [
    {"key": "1_2", "title": "Expanded sub-item", "expanded": true, "children": [
        {"key": "1_2_1", "title": "Active sub-item (active and focus on init)", "active": true, "focused": true},
        {"key": "1_2_2", "title": "Basic <i>menu item</i> with <strong class='text-semibold'>HTML support</strong>"}
    ]},
    {"key": "1_3", "title": "Expanded sub-item", "children": [
        {"key": "1_3_1", "title": "Sub-item 2.2.1"},
        {"key": "1_3_2", "title": "Sub-item 2.2.2"}
    ]}
]},
{"key": "2", "title": "Menu item with key and tooltip", "extraClasses": "has-tooltip", "tooltip": "Look, a tool tip!"},
{"key": "3", "title": "Collapsed folder", "folder": true, "children": [
    {"key": "3_1", "title": "Sub-item 1.1"},
    {"key": "3_1", "title": "Sub-item 1.2"}
]},
{"key": "4", "title": "This is a selected item", "selected": true},
{"key": "5", "title": "Document with some children (expanded on init)", "expanded": true, "children": [
    {"key": "5_1", "title": "Document sub-item"},
    {"key": "5_2", "title": "Another document sub-item", "children": [
        {"key": "5_2_1", "title": "Sub-item 2.1.1"},
        {"key": "5_2_2", "title": "Sub-item 2.1.2"}
    ]}
]}

]

Теги:
fancytree

1 ответ

0

Вы можете использовать Маршал Сериализатор, чтобы легко создать структуру.

Затем передайте сгенерированный массив функции json_encode а затем используйте его для fancytree.

TreeMapper.php

namespace MyApp\Mapper;

use KingsonDe\Marshal\AbstractMapper;
use MyApp\Data\Tree;

class TreeMapper extends AbstractMapper {

    public function map(Tree $tree) {
        $output = [
            'key'   => $tree->getKey(),
            'title' => $tree->getTitle(),
        ];

        if ($tree->isFolder()) {
            $output['folder']   = true;
            $output['children'] = $this->collection($this, $tree->getChildren()); 
        }

        return $output;
    }
}

fancytree.php

use KingsonDe\Marshal\Marshal;
use MyApp\Mapper\TreeMapper;

$treeCollection = getFancyTreeCollection();

$data = Marshal::serializeCollection(new TreeMapper(), $treeCollection);

echo json_encode($data);

Ещё вопросы

Сообщество Overcoder
Наверх
Меню