MSC
MSC

Reputation: 55

Adding to JSON with PHP

I have tried everything and it is probably very simple to solve. I want to add to a JSON object. I have searched and found examples but it does not yield the results I want. I have a JSON object that looks like this

{"d86":"2020-03-04","d76":"2020-03-05"}

Now I want to append to this so it looks like this

{"d86":"2020-03-04","d76":"2020-03-05","d97":"2020-05-08"}

The examples of how to do this give me this result

{"d86":"2020-03-04","d76":"2020-03-05","0":{"d97":"2020-03-08"}}

This is my code:

$j = array('d86'=>'2020-03-04','d76'=>'2020-03-05');

$j = json_encode($j);

$j = json_decode($j, true);

$new_date = array('d97'=>'2020-03-08');

$j[] = $new_date;

$j = json_encode($j);

print_r($j);

Upvotes: 0

Views: 34

Answers (2)

Joseph
Joseph

Reputation: 6269

In case you have multiple rows to add

you could use foreach to be like this

foreach($new_date as $key => $value){
    $j[$key] = $value;
}

so it will be like this one

$j = array('d86'=>'2020-03-04','d76'=>'2020-03-05');

$j = json_encode($j);

$j = json_decode($j, true);

$new_date = ['d97'=>'2020-03-08'];

foreach($new_date as $key => $value){
    $j[$key] = $value;
}

$j = json_encode($j);

print_r($j);

Upvotes: 0

Nick
Nick

Reputation: 147266

You can just "add" the $new_date to the existing array:

$j += $new_date;

Output:

{
    "d86": "2020-03-04",
    "d76": "2020-03-05",
    "d97": "2020-03-08"
}

Demo on 3v4l.org

Upvotes: 1

Related Questions