如何构建适当的json响应

问题描述 投票:0回答:2

我正在尝试构建一个PHP脚本,它将返回格式正确的json响应,当前我的json响应将带有反斜杠或引用内部对象。

class myObject
{
    public $property1;
    public $property2;
    public $property3;
    public $property4;
}

$MyObjects = array();

$results = DB::table('sometable')->get();

foreach ($results as $result) {
    $MyObject = new myObject;
    $MyObject->property1 = $result->col_1;
    $MyObject->property2 = $result->col_2;
    $MyObject->property3 = $result->col_3;
    //$MyObjects[] = $MyObject;
    array_push($MyObjects, $MyObject);
}

var_dump($MyObjects);
echo json_encode($MyObjects);
php json
2个回答
0
投票

要删除反斜杠,您可以写 -

echo json_encode($MyObjects, JSON_UNESCAPED_SLASHES);

-1
投票

你必须尝试下面的代码。它将返回适当的响应。

<?php

$con=mysqli_connect("localhost","root","","mydb");
$response=array();

$query="select * from studmaster";
$result=$con->query($query);

if($result->num_rows>0)
{
    $response["student"]=array();
    while($rows=$result->fetch_array(MYSQLI_BOTH))
    {
        $student=array();
        $student["studid"]=$rows["studid"];
        $student["studname"]=$rows["studname"];
        $student["studmobno"]=$rows["studmobno"];
        array_push($response ["student"],$student);
    }

    $response["status"]=1;
    $response["message"]="Data Exist";
}
else
{
    $response["status"]=0;
    $response["message"]="Data Does Not Exist";
}
echo json_encode($response);

?>
© www.soinside.com 2019 - 2024. All rights reserved.