将JSON对象格式化为JSON对象数组

时间:2014-07-08 18:59:19

标签: php arrays json slim

我一直在谷歌搜索一段时间,但还没有接近我正在寻找的东西。

从服务器上的REST API,我收到了这个回复:

{"hours":6,"day":"FRI"}{"hours":3,"day":"WEDS"}{"hours":6,"day":"MON"}{"hours":9,"day":"THUR"}{"hours":12,"day":"TUES"}{"hours":3,"day":"FRI"}

这只是一长串JSON对象。我如何让这些对象作为PHP中的JSON对象数组返回?

[ {"hours":6,"day":"FRI"}, {"hours":3,"day":"WEDS"}, {"hours":6,"day":"MON"}, {"hours":9,"day":"THUR"}, {"hours":12,"day":"TUES"}, {"hours":3,"day":"FRI"} ]

我正在使用Slim Framework,主要用于处理路由调用。

我的PHP如下:

function getHoursbyId($id) {

    $app = \Slim\Slim::getInstance();

    $query = 'SELECT hours, day FROM prof_hours
              JOIN professors ON professors.id=prof_hours.prof_id
              WHERE professors.id=?;';

    $stmt = $this->connection->prepare($query);
    $stmt->bind_param("i", $id);

    if($stmt->execute()) {
        $stmt->bind_result($hours, $day);

        while ($stmt->fetch()) {
            $result['hours'] = $hours;
            $result['day'] = $day;

            echo jsonResponse('200', $result);

        }

        $stmt->close();

        return $result;
    } else {
        return NULL;
    }

}

$result是一个数组,并传递给函数jsonResponse()

function jsonResponse($httpStatus, $response) {
$app = \Slim\Slim::getInstance();
$app->status($httpStatus);

$app->contentType('application/json');

echo json_encode($response);
}

我假设jsonResponse中的某个地方存在我的问题,但我该如何处理呢?

2 个答案:

答案 0 :(得分:1)

如何修复PHP脚本:

现在,您要分别打印每件商品。

相反,构建一个数组,最后用json_encode()回显它。

$items = array();

// adding (in the loop)
$items[] = array('hours'=>$hours, 'day'=>$day);

// at the end
echo json_encode($items);

然后您将获得有效的JSON响应。

答案 1 :(得分:0)

看起来你正在为每一行回应jsonResponse。因此,目前对于从数据库获取的每一行,您都要求应用程序回显其json_encode'd值。这就是为什么你得到一个非分隔的json对象的字符串。

您需要做的是将所有行构建为1个数组,然后将其发送到输出函数。

尝试:

...

$results = array();
while ($stmt->fetch()) {
    $results[] = array(
        'hours' => $hours,
        'day' => $day
    );
}
echo jsonResponse('200', $results);
...