PHP Search JSON File and get result -


here json file contains items. search item name , return id.

code:

 $jsonitem = file_get_contents("data.json");   $objitems = json_decode($jsonitem);    $findbyid = function($id) use ($objname) {   foreach (json_decode($objname) $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,        }     ] 

your logic correct, have couple of errors in code:

  • you referencing $objname, not set
  • you decoding data twice
  • as @mikey pointed out, json invalid because of trailing commas on "values" lines.

try:

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

Comments