在PHP中访问JSON对象元素 [英] Accessing JSON object elements in PHP

查看:362
本文介绍了在PHP中访问JSON对象元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON对象,我正在从ExtJS界面将其发布到PHP.我从

I have a JSON object that I'm POST'ING to PHP from ExtJS interface. I get the object from

$json = $_POST["newUserInfo"];

该对象将包含3个数组,我可以查看是否这样做

The object will contain 3 arrays, which I can see if I do

var_dump(json_decode($json));

我需要获取每个数组并从中构建SQL查询.我的第一个障碍是将数组移出对象,尽管这可能是不必要的.这是我正在使用的代码块:

I need to take each array and build SQL queries from them. 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);

然后,我对PERMISSIONS和SETTINGS数组重复相同的过程.这可能很简单,但我被困在这里.

Then I'd repeat the same process for PERMISSIONS and SETTINGS arrays. This is probably simple but I'm stuck here.

推荐答案

如果您使用的是json_decode($json,true);-true表示将js对象的结果作为关联数组返回-那么您要做的就是$user_info = $jsonDecoded['USER'];而没有找出原因,这就是json_decode为您做的事情.

If you are using 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']; without the array() cast cause that is what json_decode do for you.

如果您选择省略第二个布尔参数,那么您将获得一个$jsonDecoded->USER;适用的stdClass

If you would choose to omit the second boolean parameter then you will get an stdClass which $jsonDecoded->USER; would work for you

这篇关于在PHP中访问JSON对象元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆