How to pull strings out of JSON object

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 [username] => xyz ) ) ) 

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

Answers


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'].


Need Your Help

C# create multiple images and save them

c# loops save

I want to create multiple 200x200 images with a number centered on them and save them with the corresponding file name automatically to a folder. Just that, nothing more.

Where does Web API look in a Web Forms project for Controllers?

asp.net asp.net-mvc-4 asp.net-web-api

I am using Web API in my Web Forms project. I have the following code in my project's Application_Start method in Global.asax:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.