PHP JSON 二维数组输出

标签 php mysql arrays json

我已经被困在这里大约 2 个小时了,我需要一些帮助。

我想要完成的事情

我有一个 MySQL 数据库,其中有一个名为 movies 的表并且有诸如 question 之类的行, answer , category .类别很重要。由于每个类别都应打印为它自己的数组,其中的行具有该类别的值。

所有类别为 Two and a Half Men 的行应显示在 Two and a Half Men 中下面的数组。

示例:

[
  {
    "Arrow": [
      "question:","this is a question"
      "answer","this is an answer"
    ],
    "How I Met Your Mother": [
      "question:","this is a question"
      "answer","this is an answer"
    ],
    "South Park": [
      "question:","this is a question"
      "answer","this is an answer"
    ],
    "The Big Bang Theory": [
      "question:","this is a question"
      "answer","this is an answer"
    ],
    "The Last Man On Earth": [
      "question:","this is a question"
      "answer","this is an answer"
    ]
  }
]

我拥有的 JSON 输出:

[
  {
    "Arrow": [
      "question without the key value(only the string..)"
    ],
    "How I Met Your Mother": [
      "question without the key value(only the string..)"
    ],
    "South Park": [
      "question without the key value(only the string..)"
    ],
    "The Big Bang Theory": [
      "question without the key value(only the string..)"
    ],
    "The Last Man On Earth": [
      "question without the key value(only the string..)"
    ],
    "Two and a Half Men": [
      ""
    ]
  }
]

我的代码:

<?php

// Create connection
$con=mysqli_connect("localhost","username","password","db");

// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql = "SELECT * FROM movies";


if ($result = mysqli_query($con, $sql))
{
  $category = array();

  while($thearray = mysqli_fetch_array($result))
  {
    // this is the part where it gets messy. ->
    // more columns should show such as question, while the category is only the array.
      $category[$thearray['category']] = [$thearray['question']];

      array_push($category);

  }

  header('Content-Type: application/json');
  echo json_encode(array($category));


}

// Close connections
mysqli_close($con);

?>

真诚的,Jimmie!

最佳答案

使用 [] 将新元素动态添加到类别数组。您应该使用 mysqli_fetch_assoc() 只获取列名作为索引。此外,如果您想要选择所有列,则只需使用所有 $thearray:

while($thearray = mysqli_fetch_assoc($result)) {
    $category[$thearray['category']][] = $thearray;
}

或者对于特定的列:

$category[$thearray['category']][] = ['question' => $thearray['question'],
                                      'answer' => $thearray['answer']];

关于PHP JSON 二维数组输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40852170/

相关文章:

php - 如何创建一个空的 op_array?

php - 搜索结果不起作用 - mysql、php

php - 碳 diffForHumans 几个月

php - imagemagick 无法加载远程图像

c# - 从多个 sql 表 Entity Framework web api 返回数据

javascript - 为什么node.js中的mysql多语句选项会增加SQL注入(inject)的范围?

mysql - SQL几个内部连接导致错误的SUM结果

javascript - 将数组转换为包含对象的数组

java - 我的空指针异常

arrays - 尽管附加了数组,但重新加载 TableView 会根据 "empty"数组产生 0 行?