【问题标题】:Convert JSON object to associative php array将 JSON 对象转换为关联的 php 数组
【发布时间】: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

标签: php json


【解决方案1】:

您正在尝试json_decode 已解码的数据。

一旦你这样做:

$request_data = json_decode(file_get_contents("php://input"), TRUE);

您已经拥有关联数组中的信息。 (第二个参数告诉json_decode()that you want your result as an associative array and not as an object)。

下一步很简单:

$conditions = $request_data['conditions'];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    相关资源
    最近更新 更多