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...