0

I have stored a JSON ouput into as a stdClass object using json_decode.

Ideally I want to echo the property names and values for the histogram object.

I tried

echo $obj->histogram->20000();

but it doesn't seem to recognise 20000 because it's a number. Also tried '20000'.

JSON code:

{
  "location": {
    "__CLASS__": "Adzuna::API::Response::Location",
    "display_name": "Melbourne, Melbourne Region",
    "area": [
      "Australia",
      "Victoria",
      "Melbourne Region",
      "Melbourne"
    ]
  },
  "__CLASS__": "Adzuna::API::Response::SalaryHistogram",
  "histogram": {
    "20000": 2,
    "40000": 36,
    "60000": 95,
    "80000": 53,
    "100000": 27,
    "120000": 9,
    "140000": 6
  }
}
1
  • Solved it echo $json_obj->histogram->{'20000'}; Commented Nov 9, 2015 at 3:45

1 Answer 1

1

In PHP variables and class members can be just about anything, but in your PHP code they have to basically start with a normal ASCII alphabetic character or underscore (more specifically [a-zA-Z_\x7f-\xff], but in practice no one uses all the characters in that range).

To access variables that cannot be accessed using the $var format you have to use variable variables:

$name = "1twøThré3";
$value = $$name;

That is the "normal" way to use variable variables. Another way is to pass the name directly to the variable identifier:

$value = ${"1twøThré3"}

The same applies to object members:

$value = $obj->{"1twøThré3"};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.