0

I have a JSON object that can be echoed to view in a browser as follows:

stdClass Object
    (
        [webmaster] => "data"
        [analytics] => "data"
        [facebook] => "data"
        [twitter] => "data"
        [maintenance] => 1
    )

data are other values.

I get the above output using:

    $data = json_decode($domainSpecific);
    print_r($data);

what would be a good way to convert this JSON data into 5 variables preferably with the names of the JSON values - $webmaster, $analytics, $facebook, $twitter, $maintenance?

thankyou

2
  • You mean dinamically? That's it, if you add another property to the object like... myspace it would have to create automatically a var called $myspace? Commented Jan 28, 2013 at 6:45
  • yes during php execution... Commented Jan 28, 2013 at 6:46

4 Answers 4

1
$data = json_decode($domainSpecific);
foreach($data as $key=>$value)
{
    $$key=$value;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Though I'm not sure why would you do that and I'm also not sure if this is a good way to program, here you have something that works as I've tried:

class Test {
    public $webmaster, $analytics, $facebook, $twitter, $manteinance;
}

$test = new Test();
$test->webmaster = 'Trololo';

$object_vars = get_object_vars($test);

foreach ($object_vars as $varname => $value) {
    $$varname = $value;
}

echo $webmaster; //Trololo

Comments

1
$data = extract(json_decode($domainSpecific, true));
print_r($data);

Comments

1

try this php extract()

$data = json_decode($domainSpecific, TRUE);

extract($data , EXTR_PREFIX_SAME);

edit

yes you need to do json_decode with true parameter to return as array

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.