In the PHP code you provided there's no correlation between the column names and the row values. Therefore what values fall in which columns depends on the order the data is pulled from the database, which may be based on performance or insertion order, and can vary from one query to another. In order to have a predictable order, you need to specify in the query the order you want it pulled. The two queries that need to be aligned are: the one that pulls the names, and the one that pulls the values.
.
Lacking predictable ORDER:
$rez = $db->prepare("SELECT naziv FROM track_aktivnosti WHERE id_akt = :id_akt AND prvi=1 AND user_id=:user_id");
...
$result = $db->prepare("SELECT vrednost, naziv FROM track_aktivnosti WHERE id_akt = :id_akt AND datum = :datum AND user_id= :user_id");
.
Add ORDER BY naziv
at the tail end of each of these to sort the results into a predictable alignment, which then gets properly loaded in your associative array, followed by the JSON object.
Here's a tweaked version of your code, cleaning up a few other non-critical issues:
<?php
try {
$res = $db->prepare('SELECT naziv FROM track_aktivnosti WHERE id_akt = :id_akt AND user_id = :user_id AND prvi = 1 ORDER BY naziv');
$res->execute(array(':id_akt' => $_POST['id_akt'], ':user_id' => $user_id));
$kol = $res->fetchAll();
$rows = array();
$table = array();
$rows[] = array('label' => 'Datum', 'type' => 'string');
foreach ($kol as $r) {
$rows[] = array('label' => (string) $r['naziv'], 'type' => 'string');
}
$table['cols'] = $rows;
$res = $db->prepare('SELECT datum FROM track_aktivnosti WHERE id_akt = :id_akt AND user_id = :user_id GROUP BY datum ORDER BY datum');
$res->execute(array(':id_akt' => $_POST['id_akt'], ':user_id' => $user_id));
$dates = $res->fetchAll();
$rows = array();
foreach($dates as $date){
$res = $db->prepare('SELECT vrednost FROM track_aktivnosti WHERE id_akt = :id_akt AND user_id = :user_id AND datum = :datum ORDER BY naziv');
$res->execute(array(':id_akt' => $_POST['id_akt'], ':user_id' => $user_id, ':datum' => $date['datum']));
$vals = $res->fetchAll();
$m = array( array( 'v' => $date['datum'] ) );
foreach($vals as $r) {
$m[] = array('v' => (int) $r['vrednost']);
}
$rows[] = array('c' => $m);
$table['rows'] = $rows;
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo json_encode($table);
?>