D'accord, j'essaye de créer un tableau JSON à partir de mysql. Le tableau DOIT être au format suivant. J'utilise fullcalendar et je souhaite dynamiser les événements du calendrier. Ci-dessous se trouve le code qui construit le tableau, mais actuellement il n'obtient pas les informations de 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/"
)
));
Est-ce quelque chose comme ça que vous voulez faire?
$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);
Il renvoie une chaîne json dans ce format:
[{"id":"1","col1":"col1_value","col2":"col2_value"},{"id":"2","col1":"col1_value","col2":"col2_value"}]
Ou quelque chose comme ça:
$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);
La solution PDO, juste pour une meilleure implémentation alors mysql_*
:
$array = $pdo->query("SELECT id, title, '$year-month-10' as start,url
FROM table")->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($array);
La fonctionnalité intéressante est également qu'elle laissera les entiers sous forme d'entiers par opposition aux chaînes.
Juste une mise à jour pour les utilisateurs de 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);
tilisez ceci
$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).'}';