GROUP_CONCAT er nok den nemmeste loesning, men jeg kan ikke lide den loesning.
Jeg synes ikke at en streng er den rigtigte data representation i PHP.
Fremfor:
<?php
class Item {
public $dt;
public $vals;
public function __construct($dt, $vals) {
$this->dt = $dt;
$this->vals = $vals;
}
}
function load() {
$res = array();
$con = new mysqli('localhost', 'root', '', 'Test');
$stmt = $con->prepare("SELECT dt, GROUP_CONCAT(val) AS vals FROM iddtval GROUP BY dt");
$stmt->execute();
$rs = $stmt->get_result();
while($row = $rs->fetch_array(MYSQLI_ASSOC)) {
$dt = $row['dt'];
$vals = $row['vals'];
$res[] = new Item($dt, $vals);
}
$stmt->close();
$con->close();
return $res;
}
function display($data) {
foreach($data as $item) {
$dt = $item->dt;
$vals = $item->vals;
echo "$dt $vals\r\n";
}
}
$data = load();
display($data);
?>
vil jeg foretraekke:
<?php
class Item {
public $dt;
public $vals;
public function __construct($dt) {
$this->dt = $dt;
$this->vals = array();
}
}
function load() {
$res = array();
$con = new mysqli('localhost', 'root', '', 'Test');
$stmt = $con->prepare("SELECT dt, val FROM iddtval ORDER BY dt");
$stmt->execute();
$rs = $stmt->get_result();
$lastdt = 'notexisting';
while($row = $rs->fetch_array(MYSQLI_ASSOC)) {
$dt = $row['dt'];
$val = $row['val'];
if($dt != $lastdt) {
$res[] = new Item($dt);
$lastdt = $dt;
}
$res[count($res) - 1]->vals[] = $val;
}
$stmt->close();
$con->close();
return $res;
}
function display($data) {
foreach($data as $item) {
$dt = $item->dt;
$vals = implode(',', $item->vals);
echo "$dt $vals\r\n";
}
}
$data = load();
display($data);
?>