0

Maybe I am searching wrong, but I'm unable to find how to specify an Object Class in a string. Example:

I keep a list of json sites in a database, perform a foreach loop to retrieve a specific item from each site. However, each site has a different structure.

SITE 1: $result->Food->Price->Today;
SITE 2: $result->Pizza->Slice->discount;

I am trying to keep "$result->Pizza->Slice->discount" in a variable (specified in database) and return it from the class.

Sounds easy, but I'm new to class objects and all I find is how to create an object from an array.

0

3 Answers 3

1

Store this value into your database:

serialize(['Pizza', 'Slice', 'discount']);

When reading the value, unserialize it:

unserialize($value_from_db);

To retrieve the value from the JSON object use this simple function:

function retrieve_value($object, $trail) {

    foreach ($trail as $name)
        if (isset($object->$name))
            $object = $object->$name;
        else
            throw new Exception("Object does not have the property $name");

    return $object;
}

So you have something like this:

$value = retrieve_value(json_decode($json), unserialize($db_value));

Do not use eval(), because it is evil.

Sign up to request clarification or add additional context in comments.

4 Comments

d_inevitable, it works great. I'm not a fan of eval, even though this data has no user input. But the following worked perfect and simple. "var_dump( retrieve_value($data, array('return', 'sell', 'display_short')) );"
@JaredFarrish, yes I agree with you. serialize() is faster though. At least I would think it is as it contains parsing hints. So it depends on the use case. If in doubt json encoding is the way to use...
I'll give you an upvote, it's clever at least. I've heard for a while now that MySQL is going to add JSON querying as a native function. That would be interesting.
Thank you @d_inevitable, you saved me 2 days of searching. Working great.
0

A dirty way to do this would be to json encode and decode.

$array = array([Your array]);
$obj = json_decode(json_encode($array));

Haven't tested the code though.

Comments

0

I guess you could store the pathing inside the database then use "eval()" with the path on the object. Just make sure you know no one can alter the pathing because eval is dangerous with un-sanitized code!

eval("\$value = \$result->{$pathvar};");

I didn't test that, but something of the sort. Of course $pathvar would be the value of the path coming from the database, whatever variable that's stored in.

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.