开发者

How to pull strings out of JSON object

开发者 https://www.devze.com 2023-01-27 21:31 出处:网络
Here is the code $jsonString = urldecode($json); $jsonString = str_replace(\"\\\\\", \"\", $jsonString);

Here is the code

$jsonString = urldecode($json);
$jsonString = str_replace("\\", "", $jsonString);
$data = JSON_decode($jsonString);
mysql_select_db($database) or die('Cannot connect to database.');
print_r($data);

output:

  stdClass Object ( [myObject] => Array ( [0] => stdClass Object ( [fullname] => abc [role] => ADMIN [user开发者_如何学Goname] => xyz ) ) ) 

my question how can i pull individual values and insert them into the database fullname, role and username


By default json_decode turns a JSON object into a PHP object, so you'll need to access it like:

$data->myObject[0]->fullname;

When storing your data in a mysql query:

$query = "INSERT INTO table SET fullname = '{$data->myObject[0]->fullname}'";

If you prefer to use an array instead of an object, you can use:

$data = json_decode($jsonString, true); //notice the 2nd parameter

That way you can access your variables with an array like the two other posters described.

EDIT

You don't really need to use a for loop, you would just set:

$data = json_decode($jsonString, true);
$users = $data['myObject'];

Since you already have a perfectly valid array in $data['myObject'].


to get fullname:

$fullname = $data['myObject'][0]['fullname'];

Same for role/ADMIN

Which you can add to your SQL string to insert into your database.

For an example of an insert into mysql see: http://www.w3schools.com/PHP/php_mysql_insert.asp


if you do

$data = JSON_decode($jsonString, true); // just add true

then just use

$name = $data['myObject'][0]['name']; 

and save it

0

精彩评论

暂无评论...
验证码 换一张
取 消