我在php中有这个
$comment = array;
while($row = mysql_fetch_array($sqlExec, MYSQL_ASSOC)){
$comment[$row['name']] = $row['comment'];
}
echo json_encode($comment);
Having these results
{"John":"Yo","Dan":"Hello","May":"Bye"}
问题是我实际上对约翰有两条评论(Zup,Yo),但正如你所看到的,它只显示John的最后评论,即“Yo”。所以我希望John的结果是
{"John":["Yo","Sup"]}
^这可能吗?
我该怎么做?对不起,我仍然很难处理JSON。感谢
这实际上是我的完整代码
while($row = mysql_fetch_array($sqlExec, MYSQL_ASSOC)){
$comment[$row['name']] = $row['comment'];
$sql_dup = "SELECT name, COUNT(name) AS dup_count
FROM comment
GROUP BY name
HAVING (COUNT(name) > 1)
";
$sqlExec_dup = mysql_query($sql_dup, $connection);
$row_dup = mysql_fetch_array($sqlExec_dup, MYSQL_ASSOC);
if($row['name'] = $row_dup['name']){
$sql_dup2 = "SELECT * FROM comment WHERE name = '{$row['name']}'";
$sqlExec_dup2 = mysql_query($sql_dup2, $connection);
while($row_dup2 = mysql_fetch_array($sqlExec_dup2, MYSQL_ASSOC)){
$x += 1;
if($x <= $row_dup['dup_count']){
$comment[$row['name']][] = $row_dup2['comment'];
}
}
}
}
如果名称有重复,意味着它有多个评论,仍然无法获得我想要的结果。
答案 0 :(得分:2)
您必须检查它是否已经存在,如果存在,则创建一个数组(或者从头开始)
// Create arrays with names
$comment[$row['name']][] = $row['comment'];
或
// Check if there's an array
if (isset($comment[$row['name']])) {
if (is_array($comment[$row['name']])) {
$comment[$row['name']][] = $row['comment'];
} else {
$comment[$row['name']] = array($comment[$row['name']], $row['comment']);
}
} else {
$comment[$row['name']] = $row['comment'];
}
我应该指出,第一种解决方案将是非常受欢迎的,因为它会产生更多后果。
答案 1 :(得分:1)
是的,这是可能的,但您需要对此进行一些预处理:
$comment = array;
while($row = mysql_fetch_array($sqlExec, MYSQL_ASSOC)){
if(!isset($comment[$row['name']])) {
$comment[$row['name']] = array();
}
$comment[$row['name']][] = $row['comment'];
}
echo json_encode($comment);
答案 2 :(得分:0)
是的,这是可能的。而不是这一行:
$comment[$row['name']] = $row['comment'];
使用此:
$comment[$row['name']] = array('Yo', 'Sup');
用您想要的数据库中的问候语替换数组的内容。
答案 3 :(得分:0)
简单的改变:
$comment[$row['name']] = $row['comment'];
到
$comment[$row['name']][] = $row['comment'];
每次出现相同名称时,$ comment数组的每个name元素都会被覆盖。