fanbondi
fanbondi

Reputation: 1047

Associative Array PHP manipulation

I am trying to append a key value pair to the "files" key in an associative array as show below but it is taking the key-value pair outside the scope of that key.

{
  "files": [
    {
      "name": "abc.pdf",
      "size": 17915,
      "type": "application/pdf",
      "action": "NIL"
    }
  ],
  "filesize": 17344
}

I want it as specified below

{
  "files": [
    {
      "name": "abc.pdf",
      "size": 17915,
      "type": "application/pdf",
      "action": "NIL",
      "filesize": 17344
    }
  ]
}

I have tried the following but none works.

1. $data['filesize'] = $filesize; // appends as shown above
2. $data['files']['filesize'] = $filesize;//

Edit as requested, output in console.log():

   Object {files: Array[1]}
    files: Array[1]
        0:Object
            name: "abc.pdf"
            size: "1795"
            type:"application/pdf"
            action: "NIL"
        proto: Object
        length:1
__proto__:Array[0]
__proto__:Object

Upvotes: 1

Views: 337

Answers (1)

Dekel
Dekel

Reputation: 62606

Your $data['files'] is an array, where the first element is another array (and this is the array you want to change).

Try this:

$data['files'][0]['filesize'] = $data['filesize'];

If you want to completly remove the filesize in $data you can unset it:

unset($data['filesize']);

Upvotes: 1

Related Questions