首页 > 解决方案 > PHP - 创建一个包含多个数组的 JSON 对象

问题描述

我有一个 PHP 函数来创建一个目录树,但我无法格式化结果以获得这样的 JSON 文件:

[
  {
    text: 'Parent',
    href: 'parent/',
    nodes: [
      {
        text: 'Child',
        href: 'child/',
        nodes: [
          {
            text: 'Grandchild',
            href: 'grandchild/',
          },
          {
            text: 'Grandchild',
            href: 'grandchild/',
          }
        ]
      },
      {
        text: 'Child',
        href: 'child/',
      }
    ]
  },
  {
    text: 'Parent',
    href: 'parent/',
  },
  {
    text: 'Parent',
    href: 'parent/',
  },
  {
    text: 'Parent',
    href: 'parent/',
  },
  {
    text: 'Parent',
    href: 'parent/',
  },
  {
    text: 'Parent',
    href: 'parent/',
    nodes: [
      {
        text: 'Child',
        href: 'child/',
        nodes: [
          {
            text: 'Grandchild',
            href: 'grandchild/',
          },
          {
            text: 'Grandchild',
            href: 'grandchild/',
          }
        ]
      },
      {
        text: 'Child',
        href: 'child/',
      }
    ]
  }
]

这是我的PHP函数,有人可以帮助我吗?谢谢

function scandir_rec($root)
{
    $data = [];

    if (!is_dir($root)) {
        return;
    }

    $dirs = scandir($root);

    foreach ($dirs as $dir) {

        if ($dir == '.' || $dir == '..') {
            continue;
        }

        $path = $root . '/' . $dir;  

        $data[] = ['text'=>$dir, 'link'=>urlencode($path)];

        if (is_dir($path)) {

            $data[] = ['nodes' => scandir_rec($path)]; 

        }
    }

    return json_encode($data, JSON_UNESCAPED_SLASHES);
}

// init call
$rootDir = '/var/usr';

scandir_rec($rootDir);

标签: phparraysjson

解决方案


^那些人说的。

<?php
function scandir_rec($root)
{
    $data = [];

    if (!is_dir($root)) {
        return;
    }

    $dirs = scandir($root);

    foreach ($dirs as $dir) {

        if ($dir == '.' || $dir == '..') {
            continue;
        }

        $path = $root . DIRECTORY_SEPARATOR . $dir;

        if (!is_dir($path)) continue;

        $chunk = ['text' => $dir, 'link' => urlencode($path)];

        $nodes = scandir_rec($path);
        if (!empty($nodes)) $chunk['nodes'] = $nodes;

        $data[] = $chunk;
    }

    return $data;
}

$rootDir = '/var/usr';

json_encode(scandir_rec($rootDir), JSON_UNESCAPED_SLASHES);

推荐阅读