【问题标题】:How to convert this simple array into nested php array?如何将这个简单的数组转换为嵌套的 php 数组?
【发布时间】:2017-09-20 14:38:26
【问题描述】:

您好,我有一个包含类别层次结构的简单 php 数组

<?php

$categories = [
    'Games',
    '-Sports',
    '--Footbal',
    '--Basketball',
    '-Action',
    '--FPS',
    '--RPG',
    '-SIM',
];

一旦回显,它将如下所示(一个简单的类别层次结构):

Games
-Sports
--Footbal
--Basketball
-Action
--FPS
--RPG
-SIM

目前我想使用 https://github.com/jonmiles/bootstrap-treeview 的 Bootstrap Tree 插件,并且需要准备我的数据看起来像这样

var tree = [
  {
    text: "Games",
    nodes: [
      {
        text: "Sports",
        nodes: [
          {
            text: "Footbal"
          },
          {
            text: "Basketball"
          }
        ]
      },
      {
        text: "Action",
        nodes: [
          {
            text: "FPS"
          },
          {
            text: "RPG"
          }
        ]
      },
      {
        text: "SIM"
      }
    ]
  }
];

我知道我需要先构建一个数组,然后再将其转换为 JSON。问题是如何将现有数组转换为所需 JSON 的兼容数组?

到目前为止我的代码

<?php

$categories = [
    'Games',
    '-Sports',
    '--Footbal',
    '--Basketball',
    '-Action',
    '--FPS',
    '--RPG',
    '-SIM',
];

$tree_key = 0;

if (!empty($categories)) {
            foreach ($categories as $category) {

                $tree_label = $category;

                $count = substr_count($tree_label, '-');

                //if no dash (-) found, make it parent category
                if (empty($count)) {
                    $tree_key = $category;
                    $tree_array[$tree_key] = ['text'=>$category];
                }
                else
                {
                    //if one dash found, make it child of previous parent category
                    if ($count === 1) {
                        $tree_array[$tree_key]['nodes'][] = ['text'=>$category];
                    } else {

                    }
                }


            }
        }

感谢大家的帮助!

【问题讨论】:

  • 你只需要这个json对象,还是想要不管数组是什么都可以做到的代码
  • 由于树是一种递归数据模型,我建议使用递归方法来解决这个问题
  • @MatthewBergwall 取决于破折号 (-) 的数量,我想让它保持嵌套,但通常数据与上面的示例非常相似,所以如果我能做到这一点就已经很好了 :)
  • @gogaz 递归方法,我能知道我应该谷歌它吗?

标签: php mysql multidimensional-array


【解决方案1】:

试试这个:

function buildTree($data, $currentDepth = 0, $startIndex = 0) {
    $tree = array();
    foreach ($data as $i=>$c) {
        if ($i < $startIndex) {
            continue;
        }

        $depth = 0;
        if (preg_match('/^([-]*)/', $c, $m)) {
            $depth = strlen($m[1]);
        }

        if ($depth < $currentDepth) {
            break;
        } elseif ($depth != $currentDepth) {
            continue;
        }

        $node = array('text' => preg_replace('/^[-]*/', '', $c));
        $nodes = buildTree($data, $depth + 1, $i + 1);
        if (count($nodes) > 0) {    
            $node['nodes'] = $nodes;
        }

        $tree[] = $node;
    }
    return $tree;
}

$categories = [
    'Games',
    '-Sports',
    '--Footbal',
    '--Basketball',
    '-Action',
    '--FPS',
    '--RPG',
    '-SIM',
];

echo json_encode( buildTree($categories), JSON_PRETTY_PRINT );

Online demo

【讨论】:

  • 感谢您的回答完美,看着您的代码,我想知道如何才能达到编写这种代码的水平。再次感谢@brevis先生
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-25
  • 1970-01-01
  • 2018-05-15
  • 2021-08-11
  • 1970-01-01
相关资源
最近更新 更多