-5

I have following JSON data stored in a json file, and architecture of this JSON is different, so this question is not duplicate: -

Why "NULL" is generated from following PHP? : -

<?php

$url  = "file.json";
echo $url . "<br>";

$json_string = file_get_contents($url);
echo $json_string . "<br>";

$json_array = json_decode($json_string, true); // need an associative array
var_dump(json_decode($json_array));

?>

Question: if "code": "XXX" exists, how to find values of "city", "state" and "region" in PHP: -

 [
  {
    "code": "XXX",
    "city": "Indore",
    "state": "Madhya Pradesh",
    "region": "W"
  },
  {
    "code": "XXY",
    "city": "Vapi",
    "state": "Gujarat",
    "region": "W"
  },
  {
    "code": "XXZ",
    "city": "Kolkata",
    "state": "West Bengal",
    "region": "E"
  },
  {
    "code": "XXV",
    "city": "Sundar Nagar",
    "state": "Himachal Pradesh",
    "region": "N"
  }
 ]
Sukumar
  • 319
  • 3
  • 10
  • 2
    _...so this question is not duplicate_ well it is... – B001ᛦ Aug 24 '17 at 12:42
  • 2
    *"architecture of this JSON is different"* - So? There's literally an infinite number of possible JSON files; we won't answer questions about every single one. The concept of how to find something in a JSON file should only be required to be explained *once*, a *programmer* can then adapt that to the specific situation. What have you tried that didn't work? – deceze Aug 24 '17 at 12:42
  • You're trying to decode an already decoded array… – deceze Aug 24 '17 at 13:09

1 Answers1

1

try below code. First decode json then loop through it

$json = '[
  {
    "code": "XXX",
    "city": "Indore",
    "state": "Madhya Pradesh",
    "region": "W"
  },
  {
    "code": "XXY",
    "city": "Vapi",
    "state": "Gujarat",
    "region": "W"
  },
  {
    "code": "XXZ",
    "city": "Kolkata",
    "state": "West Bengal",
    "region": "E"
  },
  {
    "code": "XXV",
    "city": "Sundar Nagar",
    "state": "Himachal Pradesh",
    "region": "N"
  }
 ]';
 $arr = json_decode($json,true);
 $find_val = "XXX";
 $city = $region =$state = "";
 foreach ($arr as $key => $value) {
   if($value['code'] == $find_val)
   {
    $city = $value['city'];
    $state =$value['state'];
    $region = $value['region'];
   }
 }
 echo $city;
 echo "<br>";
 echo $state;
 echo "<br>";
 echo $region;
B. Desai
  • 16,414
  • 5
  • 26
  • 47