0

My JSON data looks like this:

[
    {
        "email":"[email protected]",
        "firstName":"test",
        "lastName":"test",
        "value":"[email protected]",
        "tokens":"[email protected]"
    },
    {
        ...
    }
]

and php data to create json file looks like this:

<?php
    session_start();
    include('connection.php');
    $userId = $_SESSION['sess_user_id'];
    $act = $_POST['action'];
    $sth = mysql_query("SELECT email, firstName, lastName, email AS value, email AS tokens FROM User");
    $rows = array();
    while($r = mysql_fetch_assoc($sth))
    {
        $rows[] = $r;
    }
    $fp = fopen('./test.json', 'w');
    fwrite($fp, json_encode($rows));
    fclose($fp);
?>

When a user is added to the database, it runs this php code:

$file = './test.json';
$data = json_decode(file_get_contents($file), true);
$newdata = array('email'=>$email, 'firstName' => $firstName, 'lastName'=>$lastName, 'value'=>$email, 'tokens'=>$email);
$data[] = $newdata;
file_put_contents($file, json_encode($data));

I want the my JSON file to look like this:

[
    {
        "email":"[email protected]",
        "firstName":"test",
        "lastName":"test",
        "value":"[email protected]",
        "tokens":[
            "[email protected]"
        ]
    }
]

I tried to figure this out, but I couldn't. Please help?

1
  • 2
    Why? [] means "array," and it doesn't look like email will have >1 value. Commented Dec 7, 2013 at 3:26

1 Answer 1

2

php handles arrays different than javascript (which differentiates between objects and arrays).

$newdata = array(
    'email'=>$email, 
    'firstName' => $firstName, 
    'lastName'=>$lastName, 
    'value'=>$email, 
    'tokens'=>array($email)
);

should do it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.