【发布时间】:2018-11-02 18:57:04
【问题描述】:
我在服务器端使用 AngularJS 和 PHP 来访问数据库。为了创建一个 POST 方法,我写了这个请求:
var req = {
method: 'POST',
url: 'action.php',
data:{'tblname': 'user',
'conditions' : {
'select' : 'user_name',
'where' : {
'user_category' : 'admin'
},
'order_by' : 'user_name'
}
};
在 PHP 中,我想将我的 JSON data 对象转换为 php 关联数组。
$request_data = json_decode(file_get_contents("php://input"));
$conditions = json_decode($request_data->conditions,true);
我使用了json_decode,但它似乎没有将 JSON 对象转换为关联 php 数组。我希望将 JSON 对象转换为以下 PHP 数组:
$conditions = array(
"select" => "user_name",
"where" =>
array("user_category" => "admin") ,
"order_by" => "user_name"
);
【问题讨论】:
-
假设
$request_data包含您期望的内容;您已经解码了数据,因此它不再是字符串而是对象。您应该将整个事物解码为数组或将conditions部分/对象转换为数组。 -
$conditions = (array) $request_data->conditions; -
我用
$conditions = (array) $request_data->conditions;替换了$conditions = json_decode($request_data->conditions,true);,现在它可以工作了。谢谢@jeroen 和@splash58