Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add data in JSON using PHP

Tags:

json

php

for-loop

I have a json file with the following syntax:

[
  {
    "fields": {
      "service_number": "service_number",
      "physical_address": "physical_address",
      "account_id": "account_id",
      "contact_id": "contact_id"
    },
    "someId": "asd23f",
    "status": "Active",
    "perCode": "1",
    "idCode": "0987",
    "nextCode": "09"
  },
  {
    "fields": {
      "service_number": "service_number",
      "physical_address": "physical_address",
      "account_id": "account_id",
      "contact_id": "contact_id"
    },
    "someId": "789096",
    "status": "Active",
    "perCode": "1",
    "idCode": "076543",
    "nextCode": "09"
  }
]

I would like to use a for loop in order to add something like a userID before or after the nextCode. Is there any solution to this? So far, I tried this:

$data = json_decode($file, true);
foreach ($data as $key => $val)
{
    foreach ($val as $key=>$c)
    {
        if (is_array($c))
            continue;
        $data .= $data . "user_id:$userId";
    }
}

Of course it does not make the trick, any ideas please?

like image 506
user2638842 Avatar asked Dec 08 '22 14:12

user2638842


1 Answers

There are a few problems.

  • First, the foreach loop works with a copy of the array it's iterating, so modifying one of the items there won't change the original array.

  • Then, your inner foreach loop is overwriting the $key from the outer loop. That would cause problems, but it's okay, because you don't actually need the inner loop.

  • Finally, after you've decoded the JSON string, $data will be an array, so appending to it with .= won't work, and even if it did, you'd just be sticking something on the end of it rather than at the specific point where your loop is.

Just refer to the specific key you need and set the value there.

$data = json_decode($file, true);
foreach ($data as $key => $val)
{
    $data[$key]['user_id'] = $userId;
}
$data = json_encode($data);
like image 116
Don't Panic Avatar answered Dec 26 '22 06:12

Don't Panic