0

Hello there!

Been a long time since I visited it DaniWeb :)

I have a very wiered problem with my JSON data I'm getting using CURL.

The returned json is 100% valid - you can copy and check it from here: http://pastebin.com/mdF1Vd7k

When I try to do the following: $result->data[0]->username; it shows nothing at all. Any idea why?

Here is my JSON Code:

$curl = curl_init($url);

//configure our curl
$options= array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => array('Content-type: application/json')
            );
//set the options to curl object
curl_setopt_array($curl, $options);

$result = curl_exec($curl);

PS: I know I can decode it to an Array which actually worked fine, but I don't like arrays. I like using it as an object as is.

Thanks in advance!

Edited by sobias

3
Contributors
2
Replies
8
Views
4 Years
Discussion Span
Last Post by jkon
1

json_decode has an option to return an object instead of an array which should be enabled by default.

Votes + Comments
As you said! you're the man!
0

First you must create the plain PHP object , its properties should be private and the getters – setters of it should be public , then you create an assigner to assign the values of the array to object using its setters. If there is a name conversion between the keys of the associative array and the names of the properties you could generalize that assigner for that kind of use without even the use of reflection.

In my point of view that is the proper OOP way , but just to mention all options , PHP has was it called “anonymous objects” that are stdClass , a generic empty class (not the parent of PHP Objects) . In my point of view this kind of object usage is not producing clean code , but this is how can be done

$anonymous = (object) array("color" => "blue", "speed" => 35,"gear" => 5);
echo $anonymous->color;

Edited by jkon

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.