I would like to add data to a json file with php.
The json file looks like this:
[
    {
        "content":"this is level 0 message 0",
        "messages": [
            {
                "content":"this is level 1 message 0",
                "messages": []
            },
            {
                "content":"this is level 1 message 1",
                "messages": []
            }
        ]
    },
    {
         "content":"this is level 0 message 1",
         "messages": []
    }
]
and can be any deep level (messages in messages in messages...).
In my post.php file I get the content of the new message (from ajax) and an array with his path where key = deep level and value = message number. For example for a new message in the "level 1 message 1":
Array (
    [0] => 0
    [1] => 1
)
I tried to make an recursive function:
function dig($path,$level,$obj) {
    if ($level < count($path)-1) {
        echo 'has children';
        dig($path,$level+1,$obj[$path[$level]]['messages'])
    } else {
        echo 'has no children';
        array_push($obj[$path[$level]]['messages'], $_POST);
        $dataJsonNew = json_encode($obj, JSON_PRETTY_PRINT);
        file_put_contents($dataFile, $dataJsonNew);
}
dig($path,0,$dataJson)
It works for the first level but not deeper because I'm loosing the path from root with the iteration.
So basically how to get
array_push($obj[0]['messages'][1]['messages'], $_POST);
from
Array (
    [0] => 0
    [1] => 1
)
(or a bigger array)
How can I fix my function ? Is there an other solution ?
edit:
Or is it possible to eval this kind of $str?
$str = "print_r($dataJson";
foreach ($path as $k) {
    $str .= "[".$k."]" . "['messages']";
}
$str .= ")";
Thank you!
 
    