Php 将同一id中的行合并到数组中

Php 将同一id中的行合并到数组中,php,mysql,Php,Mysql,我有一个句子表: ====================================================================== | id_row | id_document | id_sentence | sentence | ====================================================================== | 1 | 1 |

我有一个句子表:

======================================================================
|  id_row  |  id_document |   id_sentence   |       sentence         | 
======================================================================
|     1    |       1      |       0         | Example sentences A    |
|     2    |       1      |       1         | Example sentences B    |
|     3    |       2      |       0         | Example sentences C    |
|     4    |       2      |       1         | Example sentences D    |
======================================================================
我想将具有相同id_文档的句子合并到数组中,比如=>数组[1]=>数组[0]=>示例句子A[1]=>示例句子B[2]=>数组[0]=>示例句子C[1]=>示例句子D

代码如下:

<?php
require_once 'conf.php';
$sql = mysql_query('SELECT sentence FROM sentence group by id_document') or die(mysql_error());
while ($row = mysql_fetch_array($sql)) {
    $sentence[] = $row['sentence'];
}
print_r($sentence);
?>
但是,我只是在每个不同的id_文档中得到一句话。帮助我。谢谢:

为id\u文档上的数组编制索引,并向数组中添加新条目,如下所示:

while ($row = mysql_fetch_array($sql)) {
    $sentence[ $row['id_document'] ][] = $row['sentence'];
}
你可以写:

while ($row = mysql_fetch_array($sql))
{
   $sentence[$row['id_document']][] = $row['sentence'];
}
这是我的最终代码:

<?php

require_once 'conf.php';
$sql = mysql_query('SELECT sentence, id_document FROM sentence ') or die(mysql_error());
while ($row = mysql_fetch_array($sql)) {
   $sentence[$row['id_document']][] = $row['sentence'];
}
print_r($sentence);

?>

我试过了,得到的结果是数组[]=>数组[0]=>示例句子A[1]=>示例句子C示例句子B和示例句子D没有打印出来。我认为你没有正确复制它-请确保在等号之前添加额外的[]。我已经正确复制了它。我认为我的查询$sql=..有问题。我已经通过下面的答案修改了我的代码。cmiiw。谢谢这正是别人对你说的。你应该接受别人的回答,而不是你的复制粘贴。
<?php

require_once 'conf.php';
$sql = mysql_query('SELECT sentence, id_document FROM sentence ') or die(mysql_error());
while ($row = mysql_fetch_array($sql)) {
   $sentence[$row['id_document']][] = $row['sentence'];
}
print_r($sentence);

?>