0

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":[]}}}

1 Answers1

4

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.

Andrej Bestuzhev
  • 674
  • 6
  • 10
  • And why do you propose to reset the array at the end? – Peon Jan 30 '13 at 13:45
  • sorry, mistake: timeline = array('content' => array('pictures' => $picArray())); it will coresponds to you structure: {"timeline":{"content":{"pictures":[]}}}, so you really don't need to do first two queries. – Andrej Bestuzhev Jan 30 '13 at 14:00
  • Thank you for your answer! However, I might have formulated my question too vaguely. What I'm struggling with, is how to build a three-dimensional array from my 3 arrays, or 3 sql-queries. I am able to create an empty 3-dimensional array in PHP and encoding it to json, which then gives me the structure I want. – user2025462 Jan 31 '13 at 14:29