API响应不是正确的json形式而是数组

时间:2018-03-09 06:50:24

标签: php api web

当我试图打开带有假日列表的页面时,标题中给出了

。什么都没有打开,当我检查我的api响应时,它是数组的形式,而不是json。

我的API函数:

public static function API_getYearHolidays($year = false) {  //API
    if ($year == false) {
        $year = date('Y', time());
    }
    $q = "SELECT * FROM holidays";
    $runQuery = self::DBrunQuery($q);
    $rows = self::DBfetchRows($runQuery);
    $list = array();

    if ($year == false) {
        $list = $rows;
    } else {
        foreach ($rows as $pp) {
            $h_date = $pp['date'];
            $h_year = date('Y', strtotime($h_date));
            if ($h_year == $year) {
                $list[] = $pp;
            }
        }
    }

    if (sizeof($list) > 0) {
        foreach ($list as $key => $v) {
            $list[$key]['month'] = date('F', strtotime($v['date']));
            $list[$key]['dayOfWeek'] = date('l', 
    strtotime($v['date']));
        }
    }


    $r_error = 0;
    $return = array();
    $return['error'] = $r_error;
    $r_data['message'] = "";
    $r_data['holidays'] = $list;
    $return['data'] = $r_data;
    print_r($return) ;
    return json_encode($return);
}

我正在调用api函数的 api.php 文件:

if ($action == "get_holidays_list") {
$res = HR::API_getYearHolidays();
echo $res;

我的api回复:

Array
(
[error] => 0
[data] => Array
    (
        [message] => 
        [holidays] => Array
            (
                [0] => Array
                    (
                        [id] => 87
                        [name] => New Year
                        [date] => 2018-01-01
                        [month] => January
                        [dayOfWeek] => Monday
                    )

                [1] => Array
                    (
                        [id] => 88
                        [name] => Republic Day
                        [date] => 2018-01-26
                        [month] => January
                        [dayOfWeek] => Friday
                    ))))

并且浏览器中没有显示任何内容。 Plz帮我找到函数中的错误。感谢

1 个答案:

答案 0 :(得分:0)

这是因为你在函数API_getYearHolidays中的return语句之前有调试代码:

print_r($return) ;

对其进行评论或删除,然后再次检查。

修改
在脚本中没有打印任何内容,在api.php

中的函数调用中使用echo而不是return
if ($action == "get_holidays_list") {
    $res = HR::API_getYearHolidays();
    echo $res;