0

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);

2 Answers 2

1

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

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

3 Comments

brilliant, how i missed this one :)
Nice. I did not think you can treat an array like a string.
@MSC you're not really treating it as a string, + is a defined operator for arrays: php.net/manual/en/language.operators.array.php
0

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);

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.