[英]Restful api using Slim php returns empty if array contains arrays
在開始之前,我想讓您知道我確實是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();?>
我的設置是什么?
我也在使用Postman發送請求(我也在C#
嘗試過,都返回了空白內容)
我發現您的代碼有幾個問題。 首先,您的路線定義存在問題。 定義路由時,應將兩個參數傳遞給get
方法:模式(在您的情況下為字符串, /allfoods
)和Clousure
的實例(在情況下為可調用的路由回調,匿名函數。) 更多詳細信息在官方文檔中 。
因此,第一件事是從方法參數中刪除authenticate
字符串,並將路由定義更改為:
$app->get('/allfoods', function ($request, $response, $args) {
// Body of the function goes here
});
請注意,我還刪除了use ($app)
因為您可以使用$this
關鍵字訪問應用程序實例,因此不需要使用它( 也在官方文檔中進行了介紹 )。
第二件事是生成響應。 使用Slim框架時,始終最好返回$response
對象,而不是echo
響應( 在官方文檔中了解更多信息 )。 這會給您帶來一些優勢,例如,輔助方法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
函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.