Editor
Editor

Reputation: 632

Adding element data with Array_push to JSON file

I want to add data to existing JSON file

JSON:

{
   "s1":[
      {
         "bID":"q4a4xs",
         "bName":"Package1",
         "bStep":"slast"
      },
      {
         "bID":"q4a4xs",
         "bName":"Package2",
         "bStep":"s2"
      }
   ],
   "s2":[
      {
         "bID":"q4a4xs",
         "bName":"Package15",
         "bStep":"slast"
      }
   ]
}

I want to create data for s3

What I did?

$newdata = ['bID' => 'O4bt2xs','bName' => 'Package91','bStep' => 's1'];

$newBox = 's3';


$encDexJSON = json_decode($json);
array_push($encDexJSON->{$newBox}->{$newdata}, $newdata);

Print:

  {
   "s1":[
      {
         "bID":"q4a4xs",
         "bName":"Package1",
         "bStep":"slast"
      },
      {
         "bID":"q4a4xs",
         "bName":"Package2",
         "bStep":"s2"
      }
   ],
   "s2":[
      {
         "bID":"q4a4xs",
         "bName":"Package15",
         "bStep":"slast"
      }
   ],
   "w3":{
      "Array":null
   }
}

Where is the problem?

Upvotes: 1

Views: 51

Answers (1)

Sherif
Sherif

Reputation: 11943

To be fair, the code you provided along with the given data wouldn't even give that result. However, it's obvious that you are doing a great number of things wrong here.

For starter's you're trying to call an array on object property, which makes no sense $encDexJSON->{$newBox}->{$newdata}. That literally translates to $encDexJSON->s3->['bID' => 'O4bt2xs','bName' => 'Package91','bStep' => 's1'] which obviously makes no sense at all.

Furthermore, array_push does not do what you want here. array_push is for arrays. What you want to do is simply assign a value to a specific object property. So just do so.

$encDexJSON->$newBox = [$newdata];

Now if you wanted to simply push new objects into that array...

$encDexJSON->$newBox[] = $newdata; // this pushes value onto end of array

The array_push equivalent would be...

$encDexJSON->$newBox = [];
array_push($encDexJSON->$newBox, $newdata); // same result as above

The use of array_push tends to get in the way. It's usually cleaner just to stick to the syntax above.

Upvotes: 1

Related Questions