drju37335 2017-09-05 20:41
浏览 33

使用Hack OR PHP建模嵌套数据

I'm not sure if this is even possible, but read on if you're in for a challenge: Let's say I have a table with m columns and n rows. Each subsequent column represents a depper level in a hierarchy. Something like

GreatGrandParent | GrandParent | Parent | Child 

Let's say I get this data from the database, so I don't know how many columns there are (hence col N). But I know people like to see code, so let's say it's like this:

$data = array(
    array('sam', 'john', 'tim', 'tom'),
    array('sam', 'john', 'tim', 'dom'),
    array('sam', 'john', 'jim', 'ryan'),
    array('sam', 'john', 'jim', 'bryan'),
    array('sam', 'oscar', 'kim', 'mike'),
    array('sam', 'oscar', 'kim', 'ike'),
    array('sam', 'oscar', 'liz', 'jared'),
    array('sam', 'oscar', 'liz', 'jay'),
    array('will', 'ann', 'ray', 'jill'),
    array('will', 'ann', 'ray', 'phil'),
    array('will', 'ann', 'abe', 'henry'),
    array('will', 'ann', 'abe', 'jackie'),
    array('will', 'don', 'clive', 'katie'),
    array('will', 'don', 'clive', 'bill'),
    array('will', 'don', 'hank', 'sherlock'),
    array('will', 'don', 'hank', 'bruce'),
);

Now, if I want to have a JSON object in the form of:

{ data: {
    "sam": {
        "john": {
            "tim": ["tom", "dom"],
            "jim": ["ryan", "bryan"]
            },
        "oscar": {
              "kim": ["mike", "ike"],
              "liz": ["jared", "jay"]
       }
    },
    "will": {
    ...etc
   }
}

What is the most efficient and readable way to accomplish that IF the number of columns is not known ahead of time? Note - this question is not about JSON encoding, it's purely about how to build up the object/array that can then be run through json_encode(). Ideally a solution would be able to use any arbitrary number of columns. Please also be clear if you are making assumptions about row order. Finally - for my problem, the solution can NOT make use of references, variable variable names, dynamic variable names, etc.

--EDIT-- This is not a school problem, this is an actual problem I need to find a solution to implement. In this case, I've tried to nest two foreach loops in eachother, one for rows and another for columns, but I keep running into a wall to actually model the nested data.

I've tried to use the approach to nest a bunch of foreach loops and every time a parent changes, to use that to update the array. But I think that the best way to do this will either be recursive, or building up the vectors from the terminal node backwards...

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 运筹学排序问题中的在线排序
    • ¥30 求一段fortran代码用IVF编译运行的结果
    • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
    • ¥15 lammps拉伸应力应变曲线分析
    • ¥15 C++ 头文件/宏冲突问题解决
    • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
    • ¥50 安卓adb backup备份子用户应用数据失败
    • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
    • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
    • ¥30 python代码,帮调试,帮帮忙吧