1

I am trying to edit a JSON file with array of multiple objects.

JSON example:

$json = '{
  "MyContent": [
    {
      "I": 1,
      "A": 123,
      "B": 321,
      "ATxt": "Text (A) 1",
      "BTxt": "Text (B) 1"
    },
    {
      "I": 2,
      "A": 13,
      "B": 31,
      "ATxt": "Text (A) 2",
      "BTxt": "Text (B) 2"
    },
    {
      "I": 3,
      "A": 3,
      "B": 4,
      "ATxt": "Text (A) 3",
      "BTxt": "Text (B) 3"
    }
  ]
}';

I am trying to increment every "A" and "B" value and then convert it back to the JSON format.

I have already tried:

$decoded_json = json_decode($json);
$objects = $data->{'MyContent'};
foreach ($objects as $object)
    {
        foreach ($object as $key => $value)
        {
            if ($key == "A" || $key == "B")
            {
                $value = $value + 1;
            }
        }
    } 
$encoded_json = json_encode($objects);
echo $encoded_json;

Output from the $encoded_json is still the same. "A" and "B" values were not changed.

Miha M
  • 379
  • 1
  • 3
  • 14

0 Answers0