如何从MySQL数据库build立一个JSON数组

好吧,我一直在试图从MySQL构buildJSON数组。 数组必须是以下格式。 我正在使用fullcalendar,并希望使日历上的事件dynamic。 下面是构build数组的代码,但是目前它并没有从mysql获取信息

$year = date('Y'); $month = date('m'); echo json_encode(array( //Each array below must be pulled from database //1st record array( 'id' => 111, 'title' => "Event1", 'start' => "$year-$month-10", 'url' => "http://yahoo.com/" ), //2nd record array( 'id' => 222, 'title' => "Event2", 'start' => "$year-$month-20", 'end' => "$year-$month-22", 'url' => "http://yahoo.com/" ) )); 

是这样的事情你想做什么?

 $return_arr = array(); $fetch = mysql_query("SELECT * FROM table"); while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) { $row_array['id'] = $row['id']; $row_array['col1'] = $row['col1']; $row_array['col2'] = $row['col2']; array_push($return_arr,$row_array); } echo json_encode($return_arr); 

它以这种格式返回一个jsonstring:

 [{"id":"1","col1":"col1_value","col2":"col2_value"},{"id":"2","col1":"col1_value","col2":"col2_value"}] 

或者像这样的东西:

 $year = date('Y'); $month = date('m'); $json_array = array( //Each array below must be pulled from database //1st record array( 'id' => 111, 'title' => "Event1", 'start' => "$year-$month-10", 'url' => "http://yahoo.com/" ), //2nd record array( 'id' => 222, 'title' => "Event2", 'start' => "$year-$month-20", 'end' => "$year-$month-22", 'url' => "http://yahoo.com/" ) ); echo json_encode($json_array); 

PDO解决scheme,只是为了更好的实现,然后mysql_*

 $array = $pdo->query("SELECT id, title, '$year-month-10' as start,url FROM table")->fetchAll(PDO::FETCH_ASSOC); echo json_encode($array); 

不错的特性还在于它将整数作为整数而不是string。

只是Mysqli用户的更新:

 $base= mysqli_connect($dbhost, $dbuser, $dbpass, $dbbase); if (mysqli_connect_errno()) die('Could not connect: ' . mysql_error()); $return_arr = array(); if ($result = mysqli_query( $base, $sql )){ while ($row = mysqli_fetch_assoc($result)) { $row_array['id'] = $row['id']; $row_array['col1'] = $row['col1']; $row_array['col2'] = $row['col2']; array_push($return_arr,$row_array); } } mysqli_close($base); echo json_encode($return_arr); 

用这个

 $array = array(); $subArray=array(); $sql_results = mysql_query('SELECT * FROM `location`'); while($row = mysql_fetch_array($sql_results)) { $subArray[location_id]=$row['location']; //location_id is key and $row['location'] is value which come fron database. $subArray[x]=$row['x']; $subArray[y]=$row['y']; $array[] = $subArray ; } echo'{"ProductsData":'.json_encode($array).'}';