如何从mysql数据库构建JSON数组

时间:2011-06-08 16:17:12

标签: php mysql json

好吧,我一直在试图从mysql构建一个JSON数组。数组必须采用以下格式。我正在使用fullcalendar并希望使日历上的事件动态化。下面是构建数组的代码,但目前它没有从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/"
    )

));

3 个答案:

答案 0 :(得分:63)

这样你想做什么?

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

它以这种格式返回一个json字符串:

[{"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);

答案 1 :(得分:10)

PDO解决方案,只是为了更好地实施mysql_*

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

好的功能还在于它将整数作为整数而不是字符串。

答案 2 :(得分:1)

使用此

$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).'}';
相关问题