web-dev-qa-db-ja.com

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/"
    )

));
28
Stan Forrest

このようなことはあなたがしたいことですか?

$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);
63
jk.

PDOソリューション、単にmysql_*

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

素晴らしい機能は、文字列ではなく整数として整数を残すことです。

10
Wrikken

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);
3
AndroLogiciels

これを使用

$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).'}';