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 目详情-五一模拟赛详情页
    • ¥15 有了解d3和topogram.js库的吗?有偿请教
    • ¥100 任意维数的K均值聚类
    • ¥15 stamps做sbas-insar,时序沉降图怎么画
    • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
    • ¥15 关于#Java#的问题,如何解决?
    • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
    • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
    • ¥15 cmd cl 0x000007b
    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line