使用PHP从SQL数据库中的数组中的JSON数组

时间:2016-11-08 08:59:42

标签: php arrays json

我有以下代码:

$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;

以下JSON输出:

{
"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"
}

}

到目前为止,它看起来是正确的,但我需要摆脱0,1,2,3

等前导数字

它看起来像这样加上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"
}]

那里我做错了什么?

谢谢!

3 个答案:

答案 0 :(得分:0)

据我了解您的代码,我们为每项活动获得营业时间,因此在第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;

希望这有帮助。

答案 1 :(得分:0)

添加两个键。一个键是数字,第二个是businessHours

$retarray[] = $row;
$retarray["businessHours"] = $hoursarray;

例如,您可以将其businessHours添加到$row

$row["businessHours"] = $hoursarray;
$retarray[] = $row;

答案 2 :(得分:0)

您是否尝试过array_values($ array)?

$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 array_values($retarray);