MySQL查询表结构,使JSON友好格式

时间:2016-04-01 07:15:51

标签: php mysql sql

我希望得到这样的结果,以扩展所有节点并制作定义的树视图。

    var defaultData = [
    {
    text: 'Parent 1',
    href: '#parent1',
    tags: ['4'],
    nodes: [
      {
        text: 'Child 1',
        href: '#child1',
        tags: ['2'],
        nodes: [
          {
            text: 'Grandchild 1',
            href: '#grandchild1',
            tags: ['0']
          },
          {
            text: 'Grandchild 2',
            href: '#grandchild2',
            tags: ['0']
          }
        ]
      },
      {
        text: 'Child 2',
        href: '#child2',
        tags: ['0']
      }
    ]
  },
  {
    text: 'Parent 2',
    href: '#parent2',
    tags: ['0']
  },
  {
    text: 'Parent 3',
    href: '#parent3',
     tags: ['0']
  },
  {
    text: 'Parent 4',
    href: '#parent4',
    tags: ['0']
  },
  {
    text: 'Parent 5',
    href: '#parent5'  ,
    tags: ['0']
  }
];

我已经创建了这样的表,这是正确的吗?

enter image description here

以及如何通过 json_encode 查询结果以获得结果?

1 个答案:

答案 0 :(得分:0)

首先,您需要修复您的表格。它是高度不规则的,文本值不适用于任何语言的匹配。尝试这样的表:

$db = new mysqli('127.0.0.1', 'your_db_user', 'your_secure_password', 'your_db_schema');

if( $mysqli->connect_error ) {
    echo 'Something went wrong: ' . $mysqli->connect_error;
}

$json = [];

function sanitize_id($id) {
    return preg_replace( '/[^a-z0-9]/', '', strtolower($id) );
}

function recursive( $parentId, &$json ) {
    global $mysqli;

    if ($stmt = $mysqli->prepare("SELECT * FROM your-table WHERE parent = ?")) {

        // Bind parent id to query
        $stmt->bind_param('i', $parentId);

        $results = $stmt->execute();

        // Loop over results
        while ( $result = $results->fetch_assoc() ) {

            // Add result to JSON structure at referenced location
            $json[] = [
                'text' => $result['desc'],
                'href' => '#' . sanitize_id($result['desc']),
                'tags' => ['0'], // Are the tags another field?
                'nodes' => []
            ];

            // Rerun recusive function to check for and add any children
            recursive( $result['id'], $json['nodes'] );

        }

        $stmt->close();

    }

};

recursive(0, $json);

echo json_encode( $json );

$db->close();

id和parent应该是整数字段,desc可以是text / varchar。根或顶级项目的父值应为零(0)。

然后你可以使用类似于:

的脚本
application/json