如何使json_encode始终作为JSON数组返回?

时间:2017-12-30 04:30:19

标签: php arrays json multidimensional-array slim

这是我的代码:

  $db = connect_mysqli();

  $response = array();

  $sql = "SELECT * FROM questions ORDER BY RAND ()";
  $result = $db->query($sql);

  while($row = $result->fetch_array(MYSQL_ASSOC))
  {
    $response['answers'][$row['id']] = array('question_id'=>$row['id'], 'option_id'=>null);
  }

  echo json_encode($response);

这就是回应:

{
  answers: {
    1: {
      question_id: "1",
      option_id: null
    },
    2: {
      question_id: "2",
      option_id: null
    },
    3: {
      question_id: "3",
      option_id: null
    },
    4: {
      question_id: "4",
      option_id: null
    }
  }
}

如何使响应始终返回JSON数组?不是那样的JSON对象。有时响应是返回JSON数组,在某些部分返回JSON对象。我希望所有响应都是JSON数组。

所以,它应该是这样的:

{
  answers: [
    1: {
      question_id: "1",
      option_id: null
    },
    2: {
      question_id: "2",
      option_id: null
    },
    3: {
      question_id: "3",
      option_id: null
    },
    4: {
      question_id: "4",
      option_id: null
    }
  ]
}

3 个答案:

答案 0 :(得分:1)

它对你有帮助吗

   $response = json_encode($response);

答案 1 :(得分:1)

$response['answers'][$row['id']] = array('question_id'=>$row['id'], 'option_id'=>null);

上一行应更改为:

$response['answers'][] = array('question_id'=>$row['id'], 'option_id'=>null);

问题来自于您没有以0的索引启动数组。

答案 2 :(得分:1)

$row['id']转换为字符串以获得所需的结果。

$db = connect_mysqli();

$response = array();

$sql = "SELECT * FROM questions ORDER BY RAND ()";
$result = $db->query($sql);

while($row = $result->fetch_array(MYSQL_ASSOC))
 {
   $response['answers'][(string)$row['id']] = array('question_id'=>$row['id'], 'option_id'=>null);
 }

echo json_encode($response);