MySQL查询到Multi-Dimensional

时间:2015-10-27 06:12:49

标签: php mysql json multidimensional-array

我有一个要求,我需要从MySQL查询创建JSON文件。

查询如下:

  1. SELECT category_id, category, question, answer FROM table1;

  2. SELECT keywords FROM table2 WHERE category_id = table1.category_id;

  3. 我知道json_encode会从数组转换为JSON,但我不知道如何将数据从查询推送到下面给出的下面的多维数组结构。

    <?php
        array (
               0 => (array(
                          'Category' => 'Category 1',
                          'question' => 'Question 1',
                          'answer' => 'Answer 1',
                          'keywords' => array (
                                  0 => 'tag 1',
                                  1 => 'tag 2',
                                  2 => 'tag 3',
                                 ),
                          )
                     ),
               1 => (array(
                          'Category' => 'Category 2',
                          'question' => 'Question 2',
                          'answer' => 'Answer 2',
                          'keywords' => array (
                                  0 => 'tag 4',
                                  1 => 'tag 5',
                                  2 => 'tag 6',
                                  3 => 'tag 7',
                                 ),
                          )
                     ),
      );
    ?>
    

    下面给出了关于StackOverflow的类似问题,但没有一个能解决我的问题。

    1. mysql-queries-to-multi-dimensional-php-array

    2. php-sorting-mysql-result-to-multi-dimensional-array

2 个答案:

答案 0 :(得分:4)

试试这个

 $sql = "SELECT t1.category_id, t1.category, t1.question, t1.answer, GROUP_CONCAT(t2.keywords ORDER BY t2.keywords ASC) AS key_words
FROM table1 t1
JOIN table2 t2 ON t2.category_id = t1.category_id";

$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()) {
  $final_array['Category'] = $row['category'];
  $final_array['question'] = $row['question'];
  $final_array['answer'] = $row['answer'];
  $final_array['keywords'] = explode(',',$row['key_words']);
  $output[] = final_array;
}
print_r($output);

如果你没有使用mysqli类,

使用mysqli_query()代替$mysqli->query();

对于mysqli_fetch_assoc()

$result->fetch_assoc();

答案 1 :(得分:0)

您必须使用JOIN

SELECT t.category_id, t.category, t.question, t.answer 
FROM table1 t
LEFT JOIN keywords k 
ON k.category_id=t.category_id

之后,使用mysql_fetch_assoc()

然后Json_encode();