简体   繁体   English

在PHP中访问JSON对象元素

[英]Accessing JSON object elements in PHP

I have a JSON object that I'm POST'ING to PHP from ExtJS interface. 我有一个JSON对象,我正在从ExtJS接口发布到PHP。 I get the object from 我从中得到了这个对象

$json = $_POST["newUserInfo"];

The object will contain 3 arrays, which I can see if I do 该对象将包含3个数组,如果我这样做,我可以看到

var_dump(json_decode($json));

I need to take each array and build SQL queries from them. 我需要获取每个数组并从中构建SQL查询。 My first obstacle is getting the arrays out of the object, though this may be unnecessary. 我的第一个障碍是将数组从对象中取出,尽管这可能是不必要的。 Here is the code block I'm working from: 这是我正在使用的代码块:

/*Variable passed in from the ExtJS interface as JSON object*/
$json = $_POST["newUserInfo"];
//$json = '{"USER":{"ID":"","FULL_USER_NAME":"Some Guy","ENTERPRISE_USER_NAME":"guyso01","USER_EMAIL":"Some.Guy@Email.com","USER_PHONE":"123-456-7890"},"PERMISSIONS":{"ID":"","USER_ID":"","IS_ADMIN":"true"},"SETTINGS":{"ID":"","USERS_ID":"","BACKGROUND":"default"}}';

//Test to view the decoded output
//var_dump(json_decode($json));

//Decode the $json variable
$jsonDecoded = json_decode($json,true);

//Create arrays for each table from the $jsonDecoded object
$user_info = array($jsonDecoded['USER']);
$permissions_info = array($jsonDecoded['PERMISSIONS']);
$settings_info = array($jsonDecoded['SETTINGS']);  

I'm not creating the arrays correctly. 我没有正确创建数组。 I've also tried 我也试过了

$user_info = $jsonDecoded->USER;

and that doesn't work either. 这也不起作用。 I'm sure I'm missing something easy here. 我相信我在这里很容易丢失一些东西。 Again, this may be unnecessary as I can probably access them directly. 同样,这可能是不必要的,因为我可以直接访问它们。 I need to build the query by looping through the array and appending each key to a string and each value to a string. 我需要通过循环遍历数组并将每个键附加到字符串并将每个值附加到字符串来构建查询。 So I'd end up with something like 所以我最终得到了类似的东西

$query = "INSERT INTO USERS ($keyString) VALUES ($valueString);

Then I'd repeat the same process for PERMISSIONS and SETTINGS arrays. 然后我会为PERMISSIONS和SETTINGS数组重复相同的过程。 This is probably simple but I'm stuck here. 这可能很简单,但我被困在这里。

If you are using json_decode($json,true); 如果你使用的是json_decode($json,true); - true means returning the js objects results as associative arrays - then all you have to do is $user_info = $jsonDecoded['USER']; - true表示将js对象结果作为关联数组返回 - 那么你所要做的就是$user_info = $jsonDecoded['USER']; without the array() cast cause that is what json_decode do for you. 没有array() json_decode导致这就是json_decode为你做的事情。

If you would choose to omit the second boolean parameter then you will get an stdClass which $jsonDecoded->USER; 如果你选择省略第二个布尔参数,那么你将获得一个stdClass, $jsonDecoded->USER; would work for you 会对你有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM