1

I am using AngularJS with PHP on server side to access database. To make a POST method I write this request:

var req = {
      method: 'POST',
      url: 'action.php',
      data:{'tblname': 'user',
      'conditions' : {
            'select' : 'user_name',
            'where' : {
                 'user_category' : 'admin'
             },
       'order_by' : 'user_name'
       }   
};

In PHP I want to convert my JSON data object into a php associative array.

$request_data = json_decode(file_get_contents("php://input"));
$conditions = json_decode($request_data->conditions,true);

I used json_decode but it seems its not converting the JSON object to associative php array. I want the JSON object to be converted to the following PHP array:

$conditions = array(
        "select" => "user_name",
        "where" =>
            array("user_category" => "admin") ,
        "order_by" => "user_name"
);
3
  • 1
    Assuming that $request_data contains what you expect it to; you have already decoded the data, so it is no longer a string but an object. You should either decode the whole thing as an array or cast the conditions section / object to an array. Commented Nov 2, 2018 at 9:47
  • 1
    $conditions = (array) $request_data->conditions; Commented Nov 2, 2018 at 9:52
  • 1
    I replaced $conditions = json_decode($request_data->conditions,true); with $conditions = (array) $request_data->conditions; and now it works. Thanks @jeroen and @splash58 Commented Nov 2, 2018 at 9:55

1 Answer 1

1

You are trying to json_decode data that has already been decoded.

Once you do:

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

You've already have the information in an associative array. (The second parameter tells json_decode() that you want your result as an associative array and not as an object).

The next step is as simple as:

$conditions = $request_data['conditions'];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.