peace_love
peace_love

Reputation: 6471

How can I encode an array into json with additional data?

I am creating a json file from my array:

$file = json_encode($array);

The json file will look like this:

     [
      {
          "name": "file1.html",
          "date": "2019-01-29T20:33:57.000163Z",
          "size": "348"
      }
      {
          "name": "file2.xml",
          "date": "2019-01-29T20:33:57.000167Z",
          "size": "401"
      }
      {
          "name": "file3.html",
          "date": "2019-01-29T20:33:57.000171Z",
          "size": "1314"
      }
   ]

But I need to create a json file with some little bit different format. The output I need is:

{ 
 "draw": 1,
 "recordsTotal": 5000,
 "recordsFiltered": 5000,
 "data": [
      {
          "name": "file1.html",
          "date": "2019-01-29T20:33:57.000163Z",
          "size": "348"
      }
      {
          "name": "file2.xml",
          "date": "2019-01-29T20:33:57.000167Z",
          "size": "401"
      }
      {
          "name": "file3.html",
          "date": "2019-01-29T20:33:57.000171Z",
          "size": "1314"
      }
   ]
}

Is this possible with json_encode?

Upvotes: 1

Views: 34

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72269

Create a new array with rest of the info and assign current array data into it as well.

$newArray = array(
    'draw'=> 1,
    'recordsTotal'=> 5000,
    'recordsFiltered'=> 5000,
    'data'=>$array
);

$file = json_encode($newArray);

Upvotes: 4

Related Questions