Данные JSON не должны иметь числовое значение ключа, а результат не соответствует ожидаемому результату.

Я создаю JSON с моделью вложенного множества с использованием рекурсии. Мой результат не соответствует ожидаемому, так как этот JSON помогает мне генерировать дерево. Скобки идут не так, как в необходимом JSON.

я пытаюсь создать JSON, как это http://fperucic.github.io/treant-js/examples/evolution-tree/example6.js . Я заинтересован в nodeStructure: {}

Выпуск:

  1. у каждого ребенка есть {}, но требуется []

  2. Не требуются цифровые клавиши

  3. Ключи json не должны заключаться в кавычки, такие как «текст», «дети», «имя», они должны быть без кавычек

Онлайн компилятор: https://3v4l.org/UsXPv

<?php
$category = '{"9":{"id":"9","btc_mlm_user_id":"0","lft":"1","rht":"16","lvl":"0","name":"Root","created":"2017-06-27 05:56:11","modified":"2017-06-27 05:56:11","first_name":"","last_name":"","username":""},"42":{"id":"42","btc_mlm_user_id":"25","lft":"2","rht":"13","lvl":"1","name":"naresh","created":"2017-11-02 10:22:24","modified":"2017-11-02 10:22:24","first_name":"","last_name":"","username":"naresh"},"44":{"id":"44","btc_mlm_user_id":"27","lft":"3","rht":"4","lvl":"2","name":"rahul1","created":"2017-11-02 10:25:53","modified":"2017-11-02 10:25:53","first_name":"","last_name":"","username":"rahul1"},"45":{"id":"45","btc_mlm_user_id":"28","lft":"5","rht":"6","lvl":"2","name":"rahul123","created":"2017-11-02 10:27:19","modified":"2017-11-02 10:27:19","first_name":"","last_name":"","username":"rahul123"},"46":{"id":"46","btc_mlm_user_id":"29","lft":"7","rht":"12","lvl":"2","name":"kapil1","created":"2017-11-02 10:28:20","modified":"2017-11-02 10:28:20","first_name":"","last_name":"","username":"kapil1"},"47":{"id":"47","btc_mlm_user_id":"30","lft":"8","rht":"11","lvl":"3","name":"priya12","created":"2017-11-02 10:30:30","modified":"2017-11-02 10:30:30","first_name":"","last_name":"","username":"priya12"},"48":{"id":"48","btc_mlm_user_id":"31","lft":"9","rht":"10","lvl":"4","name":"amit12","created":"2017-11-02 10:32:00","modified":"2017-11-02 10:32:00","first_name":"","last_name":"","username":"amit12"},"43":{"id":"43","btc_mlm_user_id":"26","lft":"14","rht":"15","lvl":"1","name":"roshan","created":"2017-11-02 10:24:27","modified":"2017-11-02 10:24:27","first_name":"","last_name":"","username":"roshan"}}';

function tree($data, $left = 0, $right = null)
{
$tree = array();
foreach ($data as $key => $value)
{
if ($value['lft'] == $left + 1 && (is_null($right) || $value['rht'] < $right))
{
$tree[$key]['text']  = ['name' => $value['name']];
$tree[$key]['children'] = tree($data, $value['lft'], $value['rht']);
$left = $value['rht'];
}
}
return $tree;
}

$tree = tree(json_decode($category, true));
echo json_encode($tree);

Выход:

{
"9": {
"text": {
"name": "Root"},
"children": {
"42": {
"text": {
"name": "naresh"},
"children": {
"44": {
"text": {
"name": "rahul1"},
"children": []
},
"45": {
"text": {
"name": "rahul123"},
"children": []
},
"46": {
"text": {
"name": "kapil1"},
"children": {
"47": {
"text": {
"name": "priya12"},
"children": {
"48": {
"text": {
"name": "amit12"},
"children": []
}
}
}
}
}
}
},
"43": {
"text": {
"name": "roshan"},
"children": []
}
}
}
}

Требуемый выход:

{
text: {
name: "Root"},
children: [{
text: {
name: "naresh"},
children: [{
text: {
name: "rahul1"},
children: [
[]
],
text: {
name: "rahul123"},
children: [
[]
],
text: {
name: "kapil1"},
children: [{
text: {
name: "priya12"},
children: [{
text: {
name: "amit12"},
children: [
[]
]
}]
}]
}],
text: {
name: "roshan"},
children: [
[]
]
}]
}

Вот мои записи MySql, которые я собираю, чтобы показать вам в $ категории JSON в начале.

введите описание изображения здесь

0

Решение

Если вы хотите получить выход вы связали, а не тот, что в вашем вопросе (который является недействительным как указано @RoryMcCrossan, поскольку он содержит несколько одинаковых ключей на объект), вы можете изменить свой код следующим образом:

function tree($data, $left = 0, $right = null) {
$tree = array();
foreach ($data as $key => $value) {
if ($value['lft'] == $left + 1 && (is_null($right) || $value['rht'] < $right)) {
$child = []; // Let's make a new child
$child['text'] = ['name' => $value['name']]; // The text is required
$childTree = tree($data, $value['lft'], $value['rht']); // Let's find its children
if (!empty($childTree)) { // If it has children
$child['children'] = $childTree; // Let's save the children
}
$tree[] = $child; // Put the child in the tree
$left = $value['rht'];
}
}
return $tree;
}

$tree = tree(json_decode($category, true))[0]; // Since there's only one root, you want the first element of the tree

Вот полный код: https://3v4l.org/AYCGt

Это оставляет вас с одной проблемой, по вашему мнению, ключи не должны заключаться в кавычки. Хотя я на самом деле не знаю ваших мотивов, и он должен работать с цитатами в Javascript, вы можете сделать некоторые замены, используя preg_replace, как это:

echo preg_replace('/"(\w+)":/','$1:',json_encode($tree));

Это будет полный код: https://3v4l.org/ZaXip

3

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector