tags:

views:

62

answers:

2
+1  Q: 

json encodes aray

Okay I have been struggling with this for hours. What I am doing is creating array of what I call objects that can be moved around on a calendar.

Below is my code

$year = date('Y');
$month = date('m');

echo json_encode(array(


    array(
        'id' => 111,
        'title' => "Event3",
        'start' => "$year-$month-10",
        'url' => "http://domain.com/"
    ),

    array(
        'id' => 222,
        'title' => "Event2",
        'start' => "$year-$month-20",
        'end' => "$year-$month-22",
        'url' => "http://domain.com/"
    )

));

Now here is my problem. I need to loop through a mysql database to retrieve the information for each object. For some reason I can't get this to work. Please help

Thanks Stan

+1  A: 

Have you tried something like this?:

$mysqli = new mysqli ( 'Host', 'User', 'Pass', 'dB');

$myq = $mysqli ->query ( 'SELECT field1, field2, field3 FROM table' );

$arr_result = array();

while ( $myr = $myq->fetch_assoc () ) {
    $array = array(
      'field1' => $myr['field1'],
      'field2' => $myr['field2'],
      'field3' => $myr['field3'],
    );
    $arr_result[] = $array;
}

echo json_encode($arr_result);
dabito
That will result in a different array for each field. You want something like `$arr_result[] = array('field1' => $myr['field1'], 'field2' => $myr['field2'], 'field3'=>$myr['field3']);`
ircmaxell
@dabito I fixed your code to work. You can't repeatedly do $array[] like you had it.
ceejayoz
must have missed it, thanks =)
dabito
So far no luck. The objects are not appearing on the calendar. Again if I hand code all the objects in the array they will appear. It is only when I try to run a sql statement to get the data that they are not showing up on the calendar. Something is happening that is preventing the data from printing exactly as I have shown above in the hand coded script.
Stan Forrest
Have you print_r'ed the array before json_encoding it?
dabito
@Stan Forrest: Does your DB query return any results?
Felix Kling
Yes the query does return results. Just can't get the data returned into the proper format as it appears in the code I submitted above. If I hand code each object no problem. It's just getting the results from the database into the proper format.
Stan Forrest
A: 

If it's only the json_encode() bit that's failing, it could be due to a character encoding issue. The json_encode() function requires that all string members be valid UTF8 strings. From the json_encode() documentation:

This function only works with UTF-8 encoded data.

If your relevant database objects aren't UTF8, you'll see the function call fail.

Rob Wilkerson