1

Here is my JSON File that contains my items. I would like to search for the item name and return the id.

CODE:

 $jsonitem = file_get_contents("data.json");

 $objitems = json_decode($jsonitem);


 $findById = function($id) use ($objname) {
  foreach (json_decode($objname) as $friend) {
    if ($friend->id === $id) return $friend->name;
  }
  return;
};

echo $findById('6') ?: 'No record found.';

JSON FILE:

[
       {
          "id":1,
          "name":"Candy Wrapper",
          "value":500,
       },
       {
          "id":2,
          "name":"Torch",
          "value":2000,
       }
    ]
0

1 Answer 1

5

Your logic is correct, but you have a couple of errors in your code:

  • You are referencing $objname, which is not set
  • You are decoding the data twice
  • As @Mikey pointed out, your JSON is invalid because of trailing commas on the "values" lines.

Try:

$findById = function($id) use ($objitems) {
    foreach ($objitems as $friend) {
        if ($friend->id == $id) return $friend->name;
     }

    return false;
};
Sign up to request clarification or add additional context in comments.

3 Comments

His JSON file is also invalid because of the trailing commas on the "value" lines.
@Mikey Good catch, I didn't notice that.
As for the trailing commas sorry for the confusion, I shortened my list as they are quite expansive with game variables and such. Thanks, this solved my problem!

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.