2015-10-27 110 views
3

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

的查询如下:

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

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

我知道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

+0

什么数据库你使用的驱动程序。 mysql或mysqli –

+0

我正在使用mysqli – user4943000

回答

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();

+0

感谢您的帮助。这就是我一直在寻找的......你从写了大量的代码 – user4943000

+0

救了我,你可以标记它是正确的,如果它解决了你的问题.. –

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();