I'm currently trying to write a PHP script that returns data structured as JSON. Below you can see an example of the output I'm looking to achieve:
Array
(
[0] => GameObject
(
[id] => 1
[parent_id] => 0
[title] => Parent Page
[Rounds] => Array
(
[0] => RoundObject
(
[id] => 2
[parent_id] => 1
[title] => Sub Page
[actions] => Array
)
[1] => RoundObject
(
[id] => 2
[parent_id] => 1
[title] => Sub Page
[actions] => Array
(
[0] => ActionObject
(
[id] => 3
[parent_id] => 1
[title] => Sub Sub Page
)
[0] => ActionObject
(
[id] => 3
[parent_id] => 1
[title] => Sub Sub Page
)
)
)
)
)
[1] => GameObject
(
[id] => 4
[parent_id] => 0
[title] => Another Parent Page
)
)
The recursive function is suppose to start of with a GameObject or an array of GameObjects. Then call 'getChildren()' on the GameObjects and place the result in GameObject['Rounds']. Afterwards do the same thing with the RoundObject(s): call 'getChildren()' of the RoundObject and place the result in RoundObject['actions'].
An object such as GameObject have multiple children, children > 0. I know how the recursive function works, however I don't know how to structure the data to match my output example.
ANY HELP IS APPRECIATED! After many hours of trying different solutions I've gone desperate :).
Need clarification? Leave a comment :D
EDIT: My code currently looks like the following:
$response = create_response_object($game, $entityManager);
function create_response_object($arg, $entityManager)
{
if(is_object($arg))
{
if($arg instanceof IWithChildren)
{
//If it's an object and it implements IWithChildren -> get its children
$arg->children = $arg->getChildren($entityManager);
}
else
{
//End of the line. $arg is an object but doesn't have any children
}
}
//$arg is an array filled with objects
if(is_array($arg))
{
//If it's an array, loop through its contents
foreach ($arg as $a)
{
//$arg['child'] = create_response_object($a, $entityManager);
return create_response_object($a, $entityManager);
}
}
return $arg;
}
print_r($response);
This is what the function returns:
Game Object
(
[id:Game:private] => 9
[gamestate:Game:private] => 0
[player1ID:Game:private] => 30
[player2ID:Game:private] => 1
[currentPlayer:Game:private] => 1
[winnerID:Game:private] =>
[errorCollector:Game:private] =>
[entityManager:Game:private] =>
[children] => Array
(
[0] => Round Object
(
[id:Round:private] => 7
[winnerID:Round:private] =>
[gameID:Round:private] => 9
[roundNumber:Round:private] => 0
)
[1] => Round Object
(
[id:Round:private] => 8
[winnerID:Round:private] =>
[gameID:Round:private] => 9
[roundNumber:Round:private] => 1
)
)
)
THE EXPECTED RESPONSE: The response above seems to start of great when it adds a property called children and the value an array with children of said object. However it never goes beyond RoundObject, I want the function to continue retrieving children. I presume it has to do with the recursion in my function...