1

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

1 Answer 1

1

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']);
Sign up to request clarification or add additional context in comments.

4 Comments

Correct answer, and I can add that if you want to use a foreach you can do foreach($data['files'] as $key => $array) $array['filesize'] = $filesize;
thanks I have tried the above but getting PHP Fatal error: Cannot use object of type stdClass as array... After searching I realised I was treating an object as an array I changed your line to data->files[0]->filesize = $filesize; but now I am not even seeing filesize when I print the object.
Use var_dump on the object and update the question with the data.
console.log is javascript and your question is regarding php. Which if them?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.