如何在mysql中创建一个类别的json?

时间:2016-08-20 13:39:58

标签: php mysql angularjs json onsen-ui

我需要制作一个显示所有项目的页面,点击后会将所有可用的地方带到我这里。

我需要在mysql中创建这个

app.controller('namesCtrl', function($scope) {

 $scope.items = [
    {name: 'item1', place: ['place1', 'place2']},
    {name: 'item2', place: ['place2', 'place3']},
    {name: 'item3', place: ['place1', 'place2', 'place3']},
    {name: 'item4', place: ['place1']},
    {name: 'item5', place: ['place1', 'place2']}
];

});

我的php是

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

 $conn = new mysqli("localhost", "user", "pass", "table");

$result = $conn->query("SELECT * FROM `especialidades`");

$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
    if ($outp != "") {$outp .= ",";}

    $outp .= '{"id":"'  . $rs["id"] . '",';
    $outp .= '"nombre_especialidad":"'  . $rs["nombre_especialidad"] . '",';
    $outp .= '"aguadilla":"'   . $rs["aguadilla"] . '",';
    $outp .= '"arecibo":"'  . $rs["arecibo"] . '",';
    $outp .= '"bayamon":"'    . $rs["bayamon"]        . '",';
    $outp .= '"caguas":"'    . $rs["caguas"] . '",';
    $outp .= '"carolina":"'    . $rs["carolina"] . '",';
    $outp .= '"guayama":"'   . $rs["guayama"] . '",';
    $outp .= '"hato_rey":"' . $rs["hato_rey"] . '"}'; 
}
$outp ='{"especialidades":['.$outp.']}';
$conn->close();

echo($outp);
?>
我得到了很多错误。

如何正确地在mysql中创建它并在json中获取它。

1 个答案:

答案 0 :(得分:1)

您的代码应该是这样的

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

$conn = new mysqli("localhost", "user", "pass", "table");

$result = $conn->query("SELECT id, nombre_especialidad,aguadilla,arecibo, bayamon,caguas,carolina,guayama,hato_rey FROM `especialidades`");

$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
    $outArray["especialidades"][] = $rs;
}
$conn->close();
$outp = json_encode($outArray);
echo $outp;
?>

希望这会对你有所帮助!!