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.

4
  • stackoverflow.com/questions/15024616/… Commented Aug 28, 2020 at 13:52
  • 1
    foreach ($object as $key => &$value) Commented Aug 28, 2020 at 13:52
  • 1
    @Cid He was too fast for me - I only saw the PHP one (which I've added to the dupe list since OP is iterating an array and an object) Commented Aug 28, 2020 at 13:54
  • @Nick Thank you! That worked perfectly. Commented Aug 28, 2020 at 14:54

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.