0

我正在尝试从 json_encode 的 sql 结果创建一个关联数组。

这是我的代码:

$timelineQuery = "SELECT * FROM timeline_table";
$contentQuery = "SELECT * FROM content_table";
$picQuery = "SELECT * FROM pic_table";

$sql = mysql_query($timelineQuery) or die(mysql_error()); 
$sql2 = mysql_query($contentQuery) or die(mysql_error());
$sql3 = mysql_query($picQuery) or die(mysql_error());   

$mainArray = array(
    'timeline' => $timelineArray = array(
        'content' => $contentArray = array(
            'pictures' => $picArray = array(),
        ),
    ),
);

while($row = mysql_fetch_assoc($sql)) { 
    $timelineArray[] = $row;            
}
while($row2 = mysql_fetch_assoc($sql2)) {
    $contentArray[] = $row2;
}
while($row3 = mysql_fetch_assoc($sql3)) {
    $picArray[] = $row3;
}
echo stripslashes(json_encode($mainArray));

如果我按原样对我的 $mainArray 进行 json_encode,则返回的 json 具有我正在寻找的语法,但是如果不将其添加到数组的末尾,我就无法填充数组。

{"timeline":{"content":{"pictures":[]}}}
4

1 回答 1

4

第一的:

while($row = mysql_fetch_assoc($sql)) { 
    $timelineArray[] = $row;            
}
while($row2 = mysql_fetch_assoc($sql2)) {
    $contentArray[] = $row2;
}
while($row3 = mysql_fetch_assoc($sql3)) {
    $picArray[] = $row3;
}

然后:

    $mainArray = array(
        'timeline' => $timelineArray = array(
            'content' => $contentArray = array(
                'pictures' => $picArray = array(),
            ),
        ),
    );
echo stripslashes(json_encode($mainArray));

你用空数组定义了你的数组并且没有更新它的状态。

于 2013-01-30T13:41:49.960 回答