user2025462
user2025462

Reputation: 11

Creating an associative array in PHP from sql results, for json

I'm trying to create an associative array from sql results for json_encode.

here's my code:

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

If I json_encode my $mainArray as it is, the returned json has the syntax I'm looking for, but I've not been able to fill the array without adding it to the end of my array.

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

Upvotes: 0

Views: 962

Answers (1)

Andrej  Bestuzhev
Andrej Bestuzhev

Reputation: 674

first:

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

then:

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

you defined your array with empty arrays and didn't renew it's states.

Upvotes: 4

Related Questions