0

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!

grrr
  • 151
  • 11
  • You didn't show your value of path. If you want the message of 1.level [0], 2.level [1], 3.level [0], 4.level [5], your path has to be "0,1,0,5" or something else. In your recursive function, you use the first path element "0" and give the rest to a recursive call "1,0,5". And you only give the current element as $obj to the next recursive call. – Holger Jan 18 '18 at 14:28
  • Hello and thank you. @Holger I think that's what I do, I'm calling the `dig` function the first time with 0 as level and I'm recursively calling it with the actual level and the current element as object. Can you give me more information? – grrr Jan 18 '18 at 15:17

1 Answers1

0

Try defining this function:

function get_messages($path, $array)
{
    $index = array_shift($path);

    if ($index !== NULL)
    {
        return get_message($path, $array[$index]->messages);
    }
    else
    {
        return $array;
    }
}

Then to get the equivalent of $obj[0]['messages'][1]['messages'] do:

get_messages([0,1], $obj);

Note that what you are calling $obj is actually an array.

dhinchliff
  • 1,106
  • 8
  • 17
  • Hello and thank you. I'm passing my data from my json file as `$array` am I right? Then how to get the return? Can you give me more information? – grrr Jan 18 '18 at 15:00
  • Again thank you, this function is really nice and I get the equivalent of `$array[0]['messages'][1]['messages']` by calling `get_messages([0,1], $array);`. But I don't understand how I can append new data (`array_push($array[0]['messages'][1]['messages'], $_POST);`) and then saving them without loosing the rest of my array (see my json file in my first post/question). – grrr Jan 18 '18 at 18:55
  • With `$result = get_messages($path, $dataJson);` + `array_push($result, $_POST);` I append a new message to the target message and that's nice but I loose the whole data, so I can't update data to my json file. – grrr Jan 18 '18 at 18:58
  • Well I don't know why you are appending data to $_POST, that is an input variable, not an output variable. I also don't know what json file you want to update. Neither do I understand what you mean by losing all your data as the $dataJson variable has not been touched. Maybe you can explain what you are trying to achieve? – dhinchliff Jan 19 '18 at 09:44
  • I found an answer here : https://stackoverflow.com/questions/7508352/dynamic-array-keys and here : https://stackoverflow.com/questions/27929875/how-to-write-getter-setter-to-access-multi-level-array-by-key-names – grrr Jan 20 '18 at 09:41
  • So you wanted the opposite, I misinterpreted your array_push as it takes the parameters in the reverse order I was thinking! – dhinchliff Jan 21 '18 at 00:09
  • No problem I was not very clear I guess but anyway your code was useful for me as well! Thank you for your help! – grrr Jan 21 '18 at 17:48