如果数组包含数组,使用Slim php的Restful api将返回空

时间:2018-06-03 11:06:31

标签: php arrays rest api slim

在开始之前,我想告诉您我PHP中真的是一个菜鸟,这是我制作的第一个API。

如果我想回显一个信息数组(例如食物细节),它的效果非常好,但是当我尝试对多个项目执行相同操作时,它会返回空白。

我已经检查了调试中的变量值。它在调试中很好,我看到一个包含多个子数组的数组。

我的代码

$app->get('/allfoods', 'authenticate', function () use ($app) {
global $user_id;
$db = new FoodHandler();

// In here i get foods with their details via mysql 
$result = $db->GetAllFoods();
$response = array();
$response["error"] = false;
$response["foods"] = array();

// looping through result and preparing food array
while ($row = $result->fetch_assoc()) {
    $tmp = array();
    $tmp['food_id'] = $row['food_id'];
    $tmp['food_name'] = $row['food_name'];
    $tmp['food_desc'] = $row['food_desc'];
    $tmp['food_category'] = $row['food_category'];
    $tmp['food_creationDate'] = $row['food_creationDate'];
   array_push($response["foods"], $tmp);
}
echoRespnse(200, $response);});

我的输出函数(如果我的数组中没有数组,则效果很好)

function echoRespnse($status_code, $response) {
    $app = \Slim\Slim::getInstance();
    // Http response code
    $app->status($status_code);
    // setting response content type to json
    $app->contentType('application/json');
    echo json_encode($response);
}

$app->run();?>

我的设置是什么?

  • Localhost wamp with php 7.2.4
  • Apache 2.4.33
  • Mysql 5.7.21

我也使用邮递员发送我的请求(我也在C#尝试过,两者都回馈空内容)

1 个答案:

答案 0 :(得分:0)

我发现您的代码有几个问题。首先,您的路线定义存在问题。在定义路由时,您应该向get方法传递两个参数:一个模式(一个字符串,在您的情况下为/allfoods)和一个Clousure的实例(一个可调用的,您的路由回调) ,你的案例中的匿名函数。)More details in official docs

所以,首先要从方法参数中删除authenticate字符串,并将路由定义更改为:

$app->get('/allfoods', function ($request, $response, $args) {
    // Body of the function goes here
});

请注意我也删除了use ($app),因为您可以访问应用程序实例uising $this关键字,因此不需要(described in official docs)。

第二件事是关于产生回应。使用Slim框架时,最好返回$response对象而不是echo响应(read more in official docs)。这给您带来了一些好处,例如帮助方法whitJson可以帮助您生成JSON输出。

以更简洁的方式优化整个代码:

$app->get('/allfoods', function ($request, $response, $args) {
    global $user_id;
    $db = new FoodHandler();

    // In here i get foods with their details via mysql 
    $result = $db->GetAllFoods();
    $data= array();
    $data["error"] = false;
    $data["foods"] = array();

    // looping through result and preparing food array
    while ($row = $result->fetch_assoc()) {
        $tmp = array();
        $tmp['food_id'] = $row['food_id'];
        $tmp['food_name'] = $row['food_name'];
        $tmp['food_desc'] = $row['food_desc'];
        $tmp['food_category'] = $row['food_category'];
        $tmp['food_creationDate'] = $row['food_creationDate'];
       array_push($data["foods"], $tmp);
    }
// Return JSON data using helper method
return $response->withJson($data);
}

您将不再需要echoResponse功能。