Как я могу преобразовать результат рекурсивного запроса SQL в JSON?

У меня есть код ниже из статьи Oracle здесь (он использует 10g; я использую 11gR2),

http://www.oracle.com/technetwork/articles/bollweg-easytrees-083408.html

Работает отлично. Затем я адаптировал его к другим моим схемам. Еще работает.

Но я хочу получить его как JSON, вложенный так же, как и с тегами. Я пробовал все виды вещей, но не могу получить это. Я хочу, чтобы это стало похоже,

name:'employee'
children:[
{
name:'employee',
children:[
{
etc.

Я пытался:

    if ($row['LEVEL']==$top_level)
{
$name['children'][$node]['children'][$node]['children'][]=array('name'=>$_name . ' childLevel->' . $row['LEVEL'] .' rowNum->' . $row['ROWNUM']);
}
else
{
$name['children'][$node]['children'][]=array('name'=>$_name . ' childLevel->' . $row['LEVEL'] .' rowNum->' . $row['ROWNUM']);
}
later on json_encode($name);
...

но каждый раз он заканчивается на один слой глубже (как и ожидалось). Я попытался рекурсии, где я отправляю предыдущий идентификатор в новый запрос и избегать весь этот запрос ниже, но я не могу получить правильное вложение массива. Я понимаю, как отобразить HTML-дерево списков (я понимаю, что происходит в коде, а не просто копировать и вставлять), но не вложенный JSON.

Вот что есть в статье Oracle:

<?php
/*  file:           functional.php
phpversion: 5.1.1
version:        1.0
author:     nick bollweg <nickD0TbollwegATgmailD0Tcom>
purpose:        demonstrate basic CONNECT BY functionality with Oracle 10g
using a functional approach. */
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>CONNECT BY and array_map &raquo; a functional approach</title>
</head>
<body>
<div>
<?php

// open a connection. change these values to fit your situation
$conn = oci_connect( "scott", "tiger", "//localhost/testdb" );
$results = array();
if( !$conn ) {
exit;
}

//build a statement
$stmt = oci_parse( $conn,
"   SELECT ENAME, JOB, EMPNO, MGR, LEVEL
FROM EMP
CONNECT BY MGR = PRIOR EMPNO
START WITH MGR IS NULL
ORDER SIBLINGS BY ENAME");

// execute statement
oci_execute( $stmt );

// fetch the results
$nrows = oci_fetch_all ( $stmt, $results, 0, 0,
OCI_FETCHSTATEMENT_BY_ROW );

// we need this value accessible inside the formatting function
global $last;

// set a value not possible in a LEVEL column to allow the
// first row to know it's "firstness"$last = null;

// add a dummy "row" to cap off formatting
$results[] = array();
$formatted = array_map( "treeFunc", $results );

//output the results
echo implode( "\n",$formatted );

// clean up statement and connection
oci_free_statement( $stmt );
oci_close( $conn );

function treeFunc( $current ) {
// the previous row's level, or null on the first row
global $last;

// structural elements
$openItem =     '<li>';
$closeItem =    '</li>';
$openChildren = '<ul>';
$closeChildren =    '</ul>';
$structure = "";

if( !isset( $current['LEVEL'] ) ) {
// add closing structure(s) equal to the very last
// row's level; this will only fire for the "dummy"return str_repeat( $closeItem.$closeChildren,
$last );
}

// add the item itself
$item = "{$current['ENAME']} <i>{$current['JOB']}</i>";

if( is_null( $last ) ) {
// add the opening structure in the case of
// the first row
$structure .= $openChildren;
} elseif( $last < $current['LEVEL'] ){
// add the structure to start new branches
$structure .= $openChildren;
} elseif( $last > $current['LEVEL'] ) {
// add the structure to close branches equal to the
// difference between the previous and current levels
$structure .= $closeItem.
str_repeat( $closeChildren.$closeItem,
$last - $current['LEVEL'] );
} else {
$structure .= $closeItem;
}

// add the item structure
$structure .= $openItem;

// update $last so the next row knows whether this row is
// really its parent
$last = $current['LEVEL'];

return $structure.$item;
}
?>
</div>
</body>
</html>

2

Решение

Задача ещё не решена.

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

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

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