Billy Bones
Billy Bones

Reputation: 2965

PHP `array_push` with JSON

I have a json array (named $ourData) which currently looks something like this:

[
    //this item of $ourData named $officer_0
    {
        "code": "cg",
        "tots": [],
        "pds": []
    }
]

Now if I wanted to push some associative values to tots (something like "date" : "value"), how would I accomplish this?

Upvotes: 1

Views: 65

Answers (2)

Umer Abbas
Umer Abbas

Reputation: 1876

here is how you do it solution

$json = '[
    {
        "code": "cg",
        "tots": [],
        "pds": []
    }
]';

$arr = json_decode($json, true);

$arr[0]['tots'][] = array("date" => date('Y-m-d'));

$json = json_encode($arr);

echo $json;

Upvotes: 1

blupointmedia
blupointmedia

Reputation: 604

$data = json_decode($ourData, true);
$data['tots'][] = 'new data to add';
$ourData = json_encode($data);

Upvotes: 2

Related Questions