A
A
Alexey2021-11-08 08:55:49
PHP
Alexey, 2021-11-08 08:55:49

How to properly write data to JSON?

Hello, I just can’t understand how to write data to a JSON file so that they can be read correctly later, tell me where I made a mistake?
PHP code itself:

$user = "user213";
$token = "token213";
$d1 = array("user" => "$user", "token" => "$token");
$data[0] = $d1;
$inp = file_get_contents('tokens.json');
$tempArray = json_decode($inp);
array_push($tempArray, $data);
$jsonData = json_encode($tempArray);
file_put_contents('tokens.json', $jsonData);


As a result, I get not at all what I wanted:
[
    [{
        "user": "user212",
        "token": "token212"
    }],
    [{
        "user": "user213",
        "token": "token213"
    }]
]


Would like to get this:

{
    "users": 
    [
        {
            "user": "user1",
            "token": "token1"
        },
        {
            "user": "user2",
            "token": "token2"
        }
    ]
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
v3shin, 2021-11-08
@edlirius

$data = ['users' => [$d1]];
...
$data['users'][] = $tempArray;

O
onenull0, 2021-11-08
@onenull0

what's the problem with just wrapping it in an associative array?
$jsonData = json_encode(["users" => $tempArray]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question