从 MySQL/PHP 获取嵌套/分层 JSON

发布于 2024-08-28 23:28:02 字数 339 浏览 1 评论 0原文

我正在使用 spacetree 图表 并且我需要分层格式的 JSON。请参阅此处所需的示例 JSON 格式。我的 Mysql 数据库表中有 ID、ParentID、名称、描述字段。现在如何使用 PHP 转换分层/嵌套 JSON 中的数据? 我知道 json_encode($array)。但是,我需要嵌套/分层 php 数组。 让我知道要这样做。

I am using spacetree chart and I require JSON in hierarchical format. See sample required JSON format here. I have ID,ParentID,Name,Description fields in Mysql database table. Now How can I convert data in Hierarchical/nested JSON using PHP?
I know json_encode($array). But, I require nested/Hierarchical php array for this.
Let me know to do this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

女中豪杰 2024-09-04 23:28:02

您在这里基本上问两个问题 - 1)如何从数据库表中获取分层的 php 结构,2)如何在 json 中编码该结构。对于第一个问题,请参阅我的(旧但有效)代码。对于第二个,我相信简单的 json_encode 会工作得很好。

You're basically asking two questions here - 1) how to get an hierarchical php structure from a db table and 2) how to encode this structure in json. For the first question see, for example, my (old but working) code. For the second, I believe simple json_encode will work pretty well.

心安伴我暖 2024-09-04 23:28:02

如果您的服务器上安装了 PHP json 扩展,只需在数组上使用它即可。步骤如下:

  1. 基于 mysql 结果构建具有层次结构的 PHP 数组,
  2. 调用 json_encode($array) http://pl.php.net/manual/en/function.json-encode.php

如果您的服务器上没有启用 json_encode 并且无法安装它...您'只需要手写即可。

它会类似于(未经测试的代码警告)

function my_json_encode($array)
{
  $return = '{';
  $count = count($array);
  $i = 0;
  foreach ($array as $key => $val)
  {
    $return .= '"'.$key.'" : ';
    if (!is_array($val))
      $return .= '"'.$val.'"';
    else
      $return .= my_json_encode($val);
    if ($i < $count-1)
      $return .=",";
    $i++;
  }
  $return .= '}';
  return $return;
}

If you have PHP json extension on your server installed, just use it on an array. The steps will be:

  1. Build PHP array with hierarchy based on mysql resutls
  2. call a json_encode($array) http://pl.php.net/manual/en/function.json-encode.php

If you don't have json_encode enabled on your server and cannot install it... You'll just have to write it by hand.

It'll be something like that (untested code warning):

function my_json_encode($array)
{
  $return = '{';
  $count = count($array);
  $i = 0;
  foreach ($array as $key => $val)
  {
    $return .= '"'.$key.'" : ';
    if (!is_array($val))
      $return .= '"'.$val.'"';
    else
      $return .= my_json_encode($val);
    if ($i < $count-1)
      $return .=",";
    $i++;
  }
  $return .= '}';
  return $return;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文