Jump to content

Recommended Posts

Is there a "better" way to do this?  Desired result is PHP equivalent to {name:"my name", data: [4,6,8]}.

    private function makeNameDataObject($name,array $data)
    {
        $obj = new stdClass;
        $obj->name=$name;
        $obj->data=$data;
        return $obj;
    }
Link to comment
https://forums.phpfreaks.com/topic/301801-creating-a-stdclass-object/
Share on other sites

How about an associative array?

 

This was my first approach,, however, I am using it to add to an object created by json_decode(), it it needs to be in the form I described.

 

$obj = (object)[ 'name' => 'my name', 'data' => [2,4,6]];

 

That is what I had done after my first approach, but data also gets changed to an object which not desired.

 

looks like data is array to me

$obj = (object)[ 'name' => 'my name', 'data' => [2,4,6]];

print_r($obj);

/* results ********************

stdClass Object
(
    [name] => my name
    [data] => Array
        (
            [0] => 2
            [1] => 4
            [2] => 6
        )

)

*/

json_decode() does not force you to use objects. Pass true to the second parameter, and you get plain old associative arrays.

 

True statement, and maybe I should change my approach.  I do feel, however, objects are a little more readable and concise.

 

looks like data is array to me

 

Why, yes it does!  I swore my array got changed to an object.  Must have been some other error elsewhere.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.