如何将一个键附加到json的开头

Here is an example of what I need. I need to append the results key at the beginning of my json results

JSON

{
  "results": [ <-- this is what I need
    {
      "id": 1,
      "text": "Option 1"
    },
    {
      "id": 2,
      "text": "Option 2"
    }
  ]
}

PHP

I am creating my json results as such with php

$sql = "SELECT * FROM table";   
$result = $GLOBALS['db']->query($sql);
$i = 0;
while ($row = $result->fetch_array()) {
    $response[$i]['id'] = $row['id'];
    $response[$i]['text'] = $row['text'];
    $data['posts'][$i] = $response[$i];
    $i++;
}
if ($result->num_rows == 0) {
    echo '[]';
} else {
    echo json_encode($data['posts']);
}

Which produces

[
    {
      "id": 1,
      "text": "Option 1"
    },
    {
      "id": 2,
      "text": "Option 2"
    }
]

How can I add that results key to my JSON?

Just wrap this line echo json_encode($data['posts']); with an extra level of array index e.g results. Let's do it this way-

echo json_encode(['results'=>$data['posts']]);

Make an array with the key above json_encode

$result = array('result'=>$data['posts']);
echo json_encode($result);

You could also build the array that way in the loop:

$data['posts']['results'][$i] = $response[$i];

But to shorten the whole thing, just select what you want:

$sql = "SELECT `id`, `text` FROM `table`";   
$result = $GLOBALS['db']->query($sql);

while($data['results'][] = $result->fetch_assoc());
echo json_encode($data);