PHP JSON 2维数组输出

时间:2016-11-28 19:38:47

标签: php mysql arrays json

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

我正在努力实现的目标

我有一个MySQL数据库,其中有一个名为movies的表,其行包含questionanswercategory等行。类别很重要的地方。因为每个类别都应该打印为它自己的数组,行的值应该是该类别。

因此,所有类别为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!

1 个答案:

答案 0 :(得分:1)

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

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

或者针对特定列:

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