php mysql_fetch_assoc到json编码

时间:2017-03-10 07:38:44

标签: php mysql json

我正在使用以下代码php数组来编码Json

$query = "SELECT * FROM register WHERE email='$email'AND password='$password'AND status!='0'";

        $result = mysql_query($query) or die('Errant query:  ' . $query);
        $numResults = mysql_num_rows($result);
        if ($numResults > 0)
        {
            $data = array();
            while ($row = mysql_fetch_assoc($result))
            {
                $data = $row;

            }
        echo json_encode($data);
    }

IT给我的结果如

{"id":"26","fname":"Shankar","lname":"Salunkhe","category_name":"2"}

但我希望结果像

{"SignIn":[{"id":"26","fname":"Shankar","lname":"Salunkhe","category_name":"2"}],"errors":[],"totalNumberOfRecords":1,"responseCode":"00000"}

我该怎么做

或建议我做任何其他方法

2 个答案:

答案 0 :(得分:0)

您需要执行以下操作才能获得所需的输出。

$query = "SELECT * FROM register WHERE email='$email'AND password='$password'AND status!='0'";

        $result = mysql_query($query) or die('Errant query:  ' . $query);
        $numResults = mysql_num_rows($result);
        if ($numResults > 0)
        {
            $data = array();
            while ($row = mysql_fetch_assoc($result))
            {
                $data[] = $row;
            }
        $result = ['SignIn' => $data, 'totalNumberOfRecords' => $numResults, 'errors' => [], 'responseCode' => 0000];
        echo json_encode($result);
        exit;
    }

答案 1 :(得分:0)

您必须将所有信息存储在数组中以获得所需内容。 例如,

$data = array("id" =>"26","fname"=>"Shankar","lname"=>"Salunkhe","category_name"=>"2");

$array = array("SignIn" => $data, "errors" => [], "totalNumberOfRecords" => 1,"responseCode" => "00000");

$result = json_encode($array);