无法获得$ _POST的特定索引

时间:2015-11-19 15:14:13

标签: php

在我的代码中,我执行ajax请求并发送此内容:

Object {appointment_data: "{"id_services":["13","13"],"id_users_provider":"86…lable":false,"id":"133","id_users_customer":"87"}", customer_data: "{"first_name":"Mario","last_name":"Rossi","email":…:"","city":"","zip_code":"","notes":"","id":"87"}"}
appointment_data: "{"id_services":["13","13"],"id_users_provider":"86","start_datetime":"2015-11-19 13:43:00","end_datetime":"2015-11-19 14:55:00","notes":"","is_unavailable":false,"id":"133","id_users_customer":"87"}"
customer_data: "{"first_name":"Mario","last_name":"Rossi","email":"mrossi@net.it","phone_number":"0000","address":"","city":"","zip_code":"","notes":"","id":"87"}"

注意:此内容包含在json编码的appointment变量中:

JSON.stringify(appointment);

现在从php端,在被调用的函数内部我试图以这种方式获得约会的id

$_POST['appointment_data']['id'];

但是我收到了这个错误:

  

非法字符串偏移' id'

我也试过了.id,但同样出现了。

注意:如果我执行gettype(),我会在$_POST['appointment_data']上找到字符串 也许这就是问题?我怎么解决这个问题?

VAR DUMP PRINT

array(2) { ["appointment_data"]=> string(216) "{"id_services":["13","15","14"],"id_users_provider":"86","start_datetime":"2015-11-19 09:45:00","end_datetime":"2015-11-19 10:57:00","notes":"Appuntamento ","is_unavailable":false,"id":"131","id_users_customer":"87"}" ["customer_data"]=> string(146) "{"first_name":"Mario","last_name":"Rossi","email":"mrossi@net.it","phone_number":"0000","address":"","city":"","zip_code":"","notes":"","id":"87"}" } 

1 个答案:

答案 0 :(得分:3)

PHP不会自动将您的JSON字符串转换为对象。 HTTP POST和PHP的组合并不直观,可能不应该尝试。你对此问题的最大线索就是你的陈述:

  

如果我执行gettype(),我会在$_POST['appointment_data']

上找到字符串

在这种情况下,它是一个字符串,而一个字符串没有id索引。如果要将该JSON字符串转换为对象,PHP提供了一种方法:

$myObj = json_decode($_POST['appointment_data']);

此时,您正在寻找的价值应该可用:

$myObj->{'id'}