0

Let's assume I have the following JSON object

$object = 
{
  "recipe": {
    "apples": 5
    "flour": "2 lbs"
    "milk": "2 cartons"
  }
}

Now consider this function

private function get_quantity($ingredient) {
  $json = json_decode($object);
  return $json->recipe->{$ingredient};
}

If I pass milk to the function and want to get 2 cartons as the output. Is this possible in PHP?

6
  • 3
    yes, it's possible Commented Jul 16, 2017 at 21:10
  • 3
    well, did it work when you tried it? I'd also suggest as isset check return (isset($json->recipe->$ingredient)) ? $json->recipe->$ingredient : null; Commented Jul 16, 2017 at 21:10
  • @Scuzzy PHP isn't my native language (I'm working with C++, however my task-set requires PHP). I assumed that this might have been an improper format without trying it before-hand, and asked on stack right away. It appears stack has become my go-to for all my thoughts, before processing them myself. Commented Jul 16, 2017 at 21:14
  • It works, but you have a syntax error in your JSON: add the missing commas between the properties and you are set to go (and of course, JSON should be a string, so wrap it between single quotes) Commented Jul 16, 2017 at 21:18
  • @trincot Indeed, I'm aware, I just wrote it on the spot. Thanks for your input! Commented Jul 16, 2017 at 21:19

3 Answers 3

3

Yes, it is possible.

For reference, see:

Note $object is undefined in your function, you should pass it in as well:

private function get_quantity($object, $ingredient)
{
    $json = json_decode($object);

    return $json->recipe->{$ingredient};
}
Sign up to request clarification or add additional context in comments.

2 Comments

Let's just assume I defined $object in my constructor, and referenced it via $this. Thanks for the answer, none-the-less :)
@user2581649 I'm confused why you even asked the question. The accepted answer is exactly the same as your proposed question with the exception of the $object which you've just said doesn't really factor into the question ...
1
<?php
    $object = 
    '{
      "recipe": {
        "apples": 5,
        "flour": "2 lbs",
        "milk": "2 cartons"
      }
    }';

    function get_quantity($object, $ingredient) {
      $json = json_decode($object);
      return $json->recipe->{$ingredient};
    }

    var_dump(get_quantity($object, 'milk'));
    ?>

Comments

1

Yes, you can do it. The only problem with your code is the syntax. Try this:

$object = '
{
  "recipe": {
    "apples": 5,
    "flour": "2 lbs",
    "milk": "2 cartons"
  }
}';

Notice I added commas, and sourrounded the JSON in quotes.

The method is well defined, assuming it can see $object.

Comments

Your Answer

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