我有一个结果,$result
,从包含以下数据的SQL查询返回:[{"TOTAL":"12345"}]
我想把结果放入一个JSON API的路由,说,/api/total/
,并让它返回:{total:12345}
。我将手动设置前半部分,例如Slim框架中的'total' => whatever
。
$app->render(200, array(
'total' => $result["TOTAL"]
)
);
我如何从返回的数组引用12345
?做$result["TOTAL"]
不行
结果看起来像[{"TOTAL":"12345"}]
?
所以你必须先json_decode它
$decodedResult = json_decode($result, true);
echo $decodedResult[0]['TOTAL'];
使用此代码,您将获得值。
$result = '[{"TOTAL":"12345"}]';
$res = json_decode($result);
echo $res[0]->TOTAL;
请试试这个之前$res = json_decode($result);
即使数组中只有一个对象,它仍然是一个数组,所以您需要引用对象的索引。
$result[0]["TOTAL"]