Help referencing object properties

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Help referencing object properties

Post by flying_circus »

This is kind of a new one for me, how do I fetch a property of an object when the key contains a space?

// Notice the space in 'Panel 1'
Example: $data->design->colors->Panel 1->color;

Code: Select all

<?php
  foreach( $data->design->colors as $key => $value ) {
    print $key . "\n";
  }
?>

/* Output */
Center Flap D
Reserve Handle
Panel 3
Pinstripe D-E
Center Flap B
Cutaway Handle
Center Flap E
Center Flap C
Panel 2
Party Pinstripe B
Party Stripe
Panel 1
Legpad (Out)
Pinstripe C-D
Panel 4
Harness
Backpad
Center Flap A
Pinstripe A-B
Ring Cover
Party Pinstripe A
Pinstripe B-C
Legpad (In)
Main Risers
Binding Tape
Panel 5
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Help referencing object properties

Post by requinix »

Are you sure $data->design->colors is an object and not an array? Does array syntax work?

Otherwise,

Code: Select all

$data->design->colors->{"Panel 1"}->color
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: Help referencing object properties

Post by flying_circus »

requinix wrote:Are you sure $data->design->colors is an object and not an array? Does array syntax work?

Otherwise,

Code: Select all

$data->design->colors->{"Panel 1"}->color
Correct, it is definitely a stdClass object, array syntax does not work. I will try your suggestion above, I am interested to see if it works.

It should not be valid to have spaces in variable or method names, but this is a weird situation created by decoding a JSON object that was encoded in actionscript
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Help referencing object properties

Post by requinix »

flying_circus wrote:but this is a weird situation created by decoding a JSON object that was encoded in actionscript
If you're using json_decode() you can have it return an array instead of an object.
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: Help referencing object properties

Post by flying_circus »

requinix wrote:
flying_circus wrote:but this is a weird situation created by decoding a JSON object that was encoded in actionscript
If you're using json_decode() you can have it return an array instead of an object.
Hey, I really appreciate your feedback, you taught me something new. Between this and the last post, I should be able to solve my problem.
Post Reply