Florian Sauerwein Florian Sauerwein - 24 days ago 12
JSON Question

JSON array in array from SQL database using PHP

I have the following code:

$retarray = array();
$hoursarray = array();
$res = $this->mysqli->query("SELECT id, title, groupby FROM scheduler_activity WHERE gewerbe = '$this->gewerbe'");
while($row = $res->fetch_object()) {
$foo = $this->mysqli->query("SELECT dow, start, end FROM scheduler_businesshours WHERE activity = '$row->id'");
while($hours = $foo->fetch_object()){
$hoursarray[] = $hours;
}
$retarray[] = $row;
$retarray["businessHours"] = $hoursarray;
}
return $retarray;


And the following JSON output:

{
"0": {
"id": "1",
"title": "Spinning",
"groupby": "Trainingsgruppe"
},
"businessHours": [{
"dow": "[1,2,3]",
"start": "17:00:00",
"end": "18:00:00"
}, {
"dow": "[4,5]",
"start": "17:30:00",
"end": "18:30:00"
}],
"1": {
"id": "2",
"title": "Massage",
"groupby": "Trainingsgruppe"
},
"2": {
"id": "3",
"title": "Yoga",
"groupby": "Trainingsgruppe"
},
"3": {
"id": "4",
"title": "Dance Academy",
"groupby": "Trainingsgruppe"
}


}

So far it looks correct but I need to get rid of the leading numbers like 0, 1, 2, 3

That it will look like this plus the businessHours:

[{
"id": "1",
"title": "Spinning",
"groupby": "Trainingsgruppe"
}, {
"id": "2",
"title": "Massage",
"groupby": "Trainingsgruppe"
}, {
"id": "3",
"title": "Yoga",
"groupby": "Trainingsgruppe"
}, {
"id": "4",
"title": "Dance Academy",
"groupby": "Trainingsgruppe"
}]


What did I do wrong there?

Thank you!

Answer

As I understood about your code, we get business hour for each activity, so it's just a small change at line 10:

$retarray = array();
$hoursarray = array();
$res = $this->mysqli->query("SELECT id, title, groupby FROM scheduler_activity WHERE gewerbe = '$this->gewerbe'");
while($row = $res->fetch_object()) {
    $foo = $this->mysqli->query("SELECT dow, start, end FROM scheduler_businesshours WHERE activity = '$row->id'");
    while($hours = $foo->fetch_object()){
        $hoursarray[] = $hours;
    }
    $row["businessHours"] = $hoursarray; // Change to this, swap line 10 & 11
    $retarray[] = $row;

}
return $retarray;

Hope this helps.

Comments