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

Sta*_*est 28 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/"
    )

));
Run Code Online (Sandbox Code Playgroud)

jk.*_*jk. 64

你想做什么?

$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);
Run Code Online (Sandbox Code Playgroud)

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

[{"id":"1","col1":"col1_value","col2":"col2_value"},{"id":"2","col1":"col1_value","col2":"col2_value"}]
Run Code Online (Sandbox Code Playgroud)

或类似的东西:

$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);
Run Code Online (Sandbox Code Playgroud)

  • +1打败了我.如果所有数据库列都是正确的名称,您应该能够删除赋值并将$ row推送到数组. (2认同)

Wri*_*ken 11

PDO解决方案,只是为了更好的实现mysql_*:

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

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

  • `PDO`是_the_ defacto标准,用于连接PHP中的各种数据库,其中之一是`MySQL`.仍然使用恕我直言中的mysql扩展程序与仍然制作"HTML 3.2"页面一样糟糕.如果您的项目_really_要求它,请继续,但新代码应该没有任何关系,如果不是'PDO`,至少使用`mysqli`(注意:'`i`'代表_improved_). (3认同)