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 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

And why do you propose to reset the array at the end?
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.